From 18e67febf3573966a68c8660d6cf0e887773a80a Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 6 Oct 2021 22:53:32 +0000 Subject: [PATCH 1/2] feat: add context manager support in client chore: fix docstring for first attribute of protos committer: @busunkim96 PiperOrigin-RevId: 401271153 Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10 Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 ++++ owl-bot-staging/v1/docs/index.rst | 7 + .../v1/docs/videointelligence_v1/services.rst | 6 + .../v1/docs/videointelligence_v1/types.rst | 7 + .../video_intelligence_service.rst | 6 + .../cloud/videointelligence/__init__.py | 115 + .../google/cloud/videointelligence/py.typed | 2 + .../cloud/videointelligence_v1/__init__.py | 116 + .../videointelligence_v1/gapic_metadata.json | 33 + .../cloud/videointelligence_v1/py.typed | 2 + .../videointelligence_v1/services/__init__.py | 15 + .../video_intelligence_service/__init__.py | 22 + .../async_client.py | 274 +++ .../video_intelligence_service/client.py | 455 ++++ .../transports/__init__.py | 33 + .../transports/base.py | 191 ++ .../transports/grpc.py | 277 +++ .../transports/grpc_asyncio.py | 282 +++ .../videointelligence_v1/types/__init__.py | 112 + .../types/video_intelligence.py | 1689 ++++++++++++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 ++ .../fixup_videointelligence_v1_keywords.py | 176 ++ owl-bot-staging/v1/setup.py | 54 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/videointelligence_v1/__init__.py | 16 + .../test_video_intelligence_service.py | 1177 ++++++++++ owl-bot-staging/v1beta2/.coveragerc | 17 + owl-bot-staging/v1beta2/MANIFEST.in | 2 + owl-bot-staging/v1beta2/README.rst | 49 + owl-bot-staging/v1beta2/docs/conf.py | 376 ++++ owl-bot-staging/v1beta2/docs/index.rst | 7 + .../videointelligence_v1beta2/services.rst | 6 + .../docs/videointelligence_v1beta2/types.rst | 7 + .../video_intelligence_service.rst | 6 + .../cloud/videointelligence/__init__.py | 71 + .../google/cloud/videointelligence/py.typed | 2 + .../videointelligence_v1beta2/__init__.py | 72 + .../gapic_metadata.json | 33 + .../cloud/videointelligence_v1beta2/py.typed | 2 + .../services/__init__.py | 15 + .../video_intelligence_service/__init__.py | 22 + .../async_client.py | 274 +++ .../video_intelligence_service/client.py | 455 ++++ .../transports/__init__.py | 33 + .../transports/base.py | 191 ++ .../transports/grpc.py | 277 +++ .../transports/grpc_asyncio.py | 282 +++ .../types/__init__.py | 68 + .../types/video_intelligence.py | 718 ++++++ owl-bot-staging/v1beta2/mypy.ini | 3 + owl-bot-staging/v1beta2/noxfile.py | 132 ++ ...ixup_videointelligence_v1beta2_keywords.py | 176 ++ owl-bot-staging/v1beta2/setup.py | 54 + owl-bot-staging/v1beta2/tests/__init__.py | 16 + .../v1beta2/tests/unit/__init__.py | 16 + .../v1beta2/tests/unit/gapic/__init__.py | 16 + .../videointelligence_v1beta2/__init__.py | 16 + .../test_video_intelligence_service.py | 1177 ++++++++++ owl-bot-staging/v1p1beta1/.coveragerc | 17 + owl-bot-staging/v1p1beta1/MANIFEST.in | 2 + owl-bot-staging/v1p1beta1/README.rst | 49 + owl-bot-staging/v1p1beta1/docs/conf.py | 376 ++++ owl-bot-staging/v1p1beta1/docs/index.rst | 7 + .../videointelligence_v1p1beta1/services.rst | 6 + .../videointelligence_v1p1beta1/types.rst | 7 + .../video_intelligence_service.rst | 6 + .../cloud/videointelligence/__init__.py | 71 + .../google/cloud/videointelligence/py.typed | 2 + .../videointelligence_v1p1beta1/__init__.py | 72 + .../gapic_metadata.json | 33 + .../videointelligence_v1p1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../video_intelligence_service/__init__.py | 22 + .../async_client.py | 274 +++ .../video_intelligence_service/client.py | 455 ++++ .../transports/__init__.py | 33 + .../transports/base.py | 191 ++ .../transports/grpc.py | 277 +++ .../transports/grpc_asyncio.py | 282 +++ .../types/__init__.py | 68 + .../types/video_intelligence.py | 779 +++++++ owl-bot-staging/v1p1beta1/mypy.ini | 3 + owl-bot-staging/v1p1beta1/noxfile.py | 132 ++ ...up_videointelligence_v1p1beta1_keywords.py | 176 ++ owl-bot-staging/v1p1beta1/setup.py | 54 + owl-bot-staging/v1p1beta1/tests/__init__.py | 16 + .../v1p1beta1/tests/unit/__init__.py | 16 + .../v1p1beta1/tests/unit/gapic/__init__.py | 16 + .../videointelligence_v1p1beta1/__init__.py | 16 + .../test_video_intelligence_service.py | 1177 ++++++++++ owl-bot-staging/v1p2beta1/.coveragerc | 17 + owl-bot-staging/v1p2beta1/MANIFEST.in | 2 + owl-bot-staging/v1p2beta1/README.rst | 49 + owl-bot-staging/v1p2beta1/docs/conf.py | 376 ++++ owl-bot-staging/v1p2beta1/docs/index.rst | 7 + .../videointelligence_v1p2beta1/services.rst | 6 + .../videointelligence_v1p2beta1/types.rst | 7 + .../video_intelligence_service.rst | 6 + .../cloud/videointelligence/__init__.py | 79 + .../google/cloud/videointelligence/py.typed | 2 + .../videointelligence_v1p2beta1/__init__.py | 80 + .../gapic_metadata.json | 33 + .../videointelligence_v1p2beta1/py.typed | 2 + .../services/__init__.py | 15 + .../video_intelligence_service/__init__.py | 22 + .../async_client.py | 274 +++ .../video_intelligence_service/client.py | 455 ++++ .../transports/__init__.py | 33 + .../transports/base.py | 191 ++ .../transports/grpc.py | 277 +++ .../transports/grpc_asyncio.py | 282 +++ .../types/__init__.py | 76 + .../types/video_intelligence.py | 853 +++++++ owl-bot-staging/v1p2beta1/mypy.ini | 3 + owl-bot-staging/v1p2beta1/noxfile.py | 132 ++ ...up_videointelligence_v1p2beta1_keywords.py | 176 ++ owl-bot-staging/v1p2beta1/setup.py | 54 + owl-bot-staging/v1p2beta1/tests/__init__.py | 16 + .../v1p2beta1/tests/unit/__init__.py | 16 + .../v1p2beta1/tests/unit/gapic/__init__.py | 16 + .../videointelligence_v1p2beta1/__init__.py | 16 + .../test_video_intelligence_service.py | 1177 ++++++++++ owl-bot-staging/v1p3beta1/.coveragerc | 17 + owl-bot-staging/v1p3beta1/MANIFEST.in | 2 + owl-bot-staging/v1p3beta1/README.rst | 49 + owl-bot-staging/v1p3beta1/docs/conf.py | 376 ++++ owl-bot-staging/v1p3beta1/docs/index.rst | 7 + .../videointelligence_v1p3beta1/services.rst | 7 + .../streaming_video_intelligence_service.rst | 6 + .../videointelligence_v1p3beta1/types.rst | 7 + .../video_intelligence_service.rst | 6 + .../cloud/videointelligence/__init__.py | 145 ++ .../google/cloud/videointelligence/py.typed | 2 + .../videointelligence_v1p3beta1/__init__.py | 146 ++ .../gapic_metadata.json | 57 + .../videointelligence_v1p3beta1/py.typed | 2 + .../services/__init__.py | 15 + .../__init__.py | 22 + .../async_client.py | 224 ++ .../client.py | 401 ++++ .../transports/__init__.py | 33 + .../transports/base.py | 184 ++ .../transports/grpc.py | 257 +++ .../transports/grpc_asyncio.py | 262 +++ .../video_intelligence_service/__init__.py | 22 + .../async_client.py | 274 +++ .../video_intelligence_service/client.py | 455 ++++ .../transports/__init__.py | 33 + .../transports/base.py | 191 ++ .../transports/grpc.py | 277 +++ .../transports/grpc_asyncio.py | 282 +++ .../types/__init__.py | 138 ++ .../types/video_intelligence.py | 1998 +++++++++++++++++ owl-bot-staging/v1p3beta1/mypy.ini | 3 + owl-bot-staging/v1p3beta1/noxfile.py | 132 ++ ...up_videointelligence_v1p3beta1_keywords.py | 177 ++ owl-bot-staging/v1p3beta1/setup.py | 54 + owl-bot-staging/v1p3beta1/tests/__init__.py | 16 + .../v1p3beta1/tests/unit/__init__.py | 16 + .../v1p3beta1/tests/unit/gapic/__init__.py | 16 + .../videointelligence_v1p3beta1/__init__.py | 16 + ...st_streaming_video_intelligence_service.py | 1031 +++++++++ .../test_video_intelligence_service.py | 1177 ++++++++++ 169 files changed, 28222 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/docs/videointelligence_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/videointelligence_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py create mode 100644 owl-bot-staging/v1beta2/.coveragerc create mode 100644 owl-bot-staging/v1beta2/MANIFEST.in create mode 100644 owl-bot-staging/v1beta2/README.rst create mode 100644 owl-bot-staging/v1beta2/docs/conf.py create mode 100644 owl-bot-staging/v1beta2/docs/index.rst create mode 100644 owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst create mode 100644 owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst create mode 100644 owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py create mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py create mode 100644 owl-bot-staging/v1beta2/mypy.ini create mode 100644 owl-bot-staging/v1beta2/noxfile.py create mode 100644 owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py create mode 100644 owl-bot-staging/v1beta2/setup.py create mode 100644 owl-bot-staging/v1beta2/tests/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py create mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py create mode 100644 owl-bot-staging/v1p1beta1/.coveragerc create mode 100644 owl-bot-staging/v1p1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p1beta1/README.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py create mode 100644 owl-bot-staging/v1p1beta1/mypy.ini create mode 100644 owl-bot-staging/v1p1beta1/noxfile.py create mode 100644 owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py create mode 100644 owl-bot-staging/v1p1beta1/setup.py create mode 100644 owl-bot-staging/v1p1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py create mode 100644 owl-bot-staging/v1p2beta1/.coveragerc create mode 100644 owl-bot-staging/v1p2beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p2beta1/README.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p2beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py create mode 100644 owl-bot-staging/v1p2beta1/mypy.ini create mode 100644 owl-bot-staging/v1p2beta1/noxfile.py create mode 100644 owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py create mode 100644 owl-bot-staging/v1p2beta1/setup.py create mode 100644 owl-bot-staging/v1p2beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py create mode 100644 owl-bot-staging/v1p3beta1/.coveragerc create mode 100644 owl-bot-staging/v1p3beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p3beta1/README.rst create mode 100644 owl-bot-staging/v1p3beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p3beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst create mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst create mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst create mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py create mode 100644 owl-bot-staging/v1p3beta1/mypy.ini create mode 100644 owl-bot-staging/v1p3beta1/noxfile.py create mode 100644 owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py create mode 100644 owl-bot-staging/v1p3beta1/setup.py create mode 100644 owl-bot-staging/v1p3beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py create mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py create mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..45c608f8 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/videointelligence/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 00000000..7e4e1e18 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/videointelligence *.py +recursive-include google/cloud/videointelligence_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..bedc3680 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Videointelligence API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Videointelligence API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..7a82f64b --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-videointelligence documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-videointelligence" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-videointelligence-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-videointelligence.tex", + u"google-cloud-videointelligence Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-videointelligence", + u"Google Cloud Videointelligence Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-videointelligence", + u"google-cloud-videointelligence Documentation", + author, + "google-cloud-videointelligence", + "GAPIC library for Google Cloud Videointelligence API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..edb2525a --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + videointelligence_v1/services + videointelligence_v1/types diff --git a/owl-bot-staging/v1/docs/videointelligence_v1/services.rst b/owl-bot-staging/v1/docs/videointelligence_v1/services.rst new file mode 100644 index 00000000..ed2a27c6 --- /dev/null +++ b/owl-bot-staging/v1/docs/videointelligence_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Videointelligence v1 API +================================================== +.. toctree:: + :maxdepth: 2 + + video_intelligence_service diff --git a/owl-bot-staging/v1/docs/videointelligence_v1/types.rst b/owl-bot-staging/v1/docs/videointelligence_v1/types.rst new file mode 100644 index 00000000..6bada002 --- /dev/null +++ b/owl-bot-staging/v1/docs/videointelligence_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Videointelligence v1 API +=============================================== + +.. automodule:: google.cloud.videointelligence_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst b/owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst new file mode 100644 index 00000000..d8d38ca3 --- /dev/null +++ b/owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst @@ -0,0 +1,6 @@ +VideoIntelligenceService +------------------------------------------ + +.. automodule:: google.cloud.videointelligence_v1.services.video_intelligence_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence/__init__.py new file mode 100644 index 00000000..b3b8fdb7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence/__init__.py @@ -0,0 +1,115 @@ +# -*- 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.videointelligence_v1.services.video_intelligence_service.client import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient + +from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoProgress +from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoRequest +from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoResponse +from google.cloud.videointelligence_v1.types.video_intelligence import DetectedAttribute +from google.cloud.videointelligence_v1.types.video_intelligence import DetectedLandmark +from google.cloud.videointelligence_v1.types.video_intelligence import Entity +from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentDetectionConfig +from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentFrame +from google.cloud.videointelligence_v1.types.video_intelligence import FaceAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionConfig +from google.cloud.videointelligence_v1.types.video_intelligence import FaceFrame +from google.cloud.videointelligence_v1.types.video_intelligence import FaceSegment +from google.cloud.videointelligence_v1.types.video_intelligence import LabelAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionConfig +from google.cloud.videointelligence_v1.types.video_intelligence import LabelFrame +from google.cloud.videointelligence_v1.types.video_intelligence import LabelSegment +from google.cloud.videointelligence_v1.types.video_intelligence import LogoRecognitionAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingBox +from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingPoly +from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedVertex +from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingConfig +from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingFrame +from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionConfig +from google.cloud.videointelligence_v1.types.video_intelligence import ShotChangeDetectionConfig +from google.cloud.videointelligence_v1.types.video_intelligence import SpeechContext +from google.cloud.videointelligence_v1.types.video_intelligence import SpeechRecognitionAlternative +from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscription +from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscriptionConfig +from google.cloud.videointelligence_v1.types.video_intelligence import TextAnnotation +from google.cloud.videointelligence_v1.types.video_intelligence import TextDetectionConfig +from google.cloud.videointelligence_v1.types.video_intelligence import TextFrame +from google.cloud.videointelligence_v1.types.video_intelligence import TextSegment +from google.cloud.videointelligence_v1.types.video_intelligence import TimestampedObject +from google.cloud.videointelligence_v1.types.video_intelligence import Track +from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationProgress +from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationResults +from google.cloud.videointelligence_v1.types.video_intelligence import VideoContext +from google.cloud.videointelligence_v1.types.video_intelligence import VideoSegment +from google.cloud.videointelligence_v1.types.video_intelligence import WordInfo +from google.cloud.videointelligence_v1.types.video_intelligence import Feature +from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionMode +from google.cloud.videointelligence_v1.types.video_intelligence import Likelihood + +__all__ = ('VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'DetectedAttribute', + 'DetectedLandmark', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'FaceAnnotation', + 'FaceDetectionAnnotation', + 'FaceDetectionConfig', + 'FaceFrame', + 'FaceSegment', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'LogoRecognitionAnnotation', + 'NormalizedBoundingBox', + 'NormalizedBoundingPoly', + 'NormalizedVertex', + 'ObjectTrackingAnnotation', + 'ObjectTrackingConfig', + 'ObjectTrackingFrame', + 'PersonDetectionAnnotation', + 'PersonDetectionConfig', + 'ShotChangeDetectionConfig', + 'SpeechContext', + 'SpeechRecognitionAlternative', + 'SpeechTranscription', + 'SpeechTranscriptionConfig', + 'TextAnnotation', + 'TextDetectionConfig', + 'TextFrame', + 'TextSegment', + 'TimestampedObject', + 'Track', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'WordInfo', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1/google/cloud/videointelligence/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py new file mode 100644 index 00000000..24afe1d1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.video_intelligence_service import VideoIntelligenceServiceClient +from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient + +from .types.video_intelligence import AnnotateVideoProgress +from .types.video_intelligence import AnnotateVideoRequest +from .types.video_intelligence import AnnotateVideoResponse +from .types.video_intelligence import DetectedAttribute +from .types.video_intelligence import DetectedLandmark +from .types.video_intelligence import Entity +from .types.video_intelligence import ExplicitContentAnnotation +from .types.video_intelligence import ExplicitContentDetectionConfig +from .types.video_intelligence import ExplicitContentFrame +from .types.video_intelligence import FaceAnnotation +from .types.video_intelligence import FaceDetectionAnnotation +from .types.video_intelligence import FaceDetectionConfig +from .types.video_intelligence import FaceFrame +from .types.video_intelligence import FaceSegment +from .types.video_intelligence import LabelAnnotation +from .types.video_intelligence import LabelDetectionConfig +from .types.video_intelligence import LabelFrame +from .types.video_intelligence import LabelSegment +from .types.video_intelligence import LogoRecognitionAnnotation +from .types.video_intelligence import NormalizedBoundingBox +from .types.video_intelligence import NormalizedBoundingPoly +from .types.video_intelligence import NormalizedVertex +from .types.video_intelligence import ObjectTrackingAnnotation +from .types.video_intelligence import ObjectTrackingConfig +from .types.video_intelligence import ObjectTrackingFrame +from .types.video_intelligence import PersonDetectionAnnotation +from .types.video_intelligence import PersonDetectionConfig +from .types.video_intelligence import ShotChangeDetectionConfig +from .types.video_intelligence import SpeechContext +from .types.video_intelligence import SpeechRecognitionAlternative +from .types.video_intelligence import SpeechTranscription +from .types.video_intelligence import SpeechTranscriptionConfig +from .types.video_intelligence import TextAnnotation +from .types.video_intelligence import TextDetectionConfig +from .types.video_intelligence import TextFrame +from .types.video_intelligence import TextSegment +from .types.video_intelligence import TimestampedObject +from .types.video_intelligence import Track +from .types.video_intelligence import VideoAnnotationProgress +from .types.video_intelligence import VideoAnnotationResults +from .types.video_intelligence import VideoContext +from .types.video_intelligence import VideoSegment +from .types.video_intelligence import WordInfo +from .types.video_intelligence import Feature +from .types.video_intelligence import LabelDetectionMode +from .types.video_intelligence import Likelihood + +__all__ = ( + 'VideoIntelligenceServiceAsyncClient', +'AnnotateVideoProgress', +'AnnotateVideoRequest', +'AnnotateVideoResponse', +'DetectedAttribute', +'DetectedLandmark', +'Entity', +'ExplicitContentAnnotation', +'ExplicitContentDetectionConfig', +'ExplicitContentFrame', +'FaceAnnotation', +'FaceDetectionAnnotation', +'FaceDetectionConfig', +'FaceFrame', +'FaceSegment', +'Feature', +'LabelAnnotation', +'LabelDetectionConfig', +'LabelDetectionMode', +'LabelFrame', +'LabelSegment', +'Likelihood', +'LogoRecognitionAnnotation', +'NormalizedBoundingBox', +'NormalizedBoundingPoly', +'NormalizedVertex', +'ObjectTrackingAnnotation', +'ObjectTrackingConfig', +'ObjectTrackingFrame', +'PersonDetectionAnnotation', +'PersonDetectionConfig', +'ShotChangeDetectionConfig', +'SpeechContext', +'SpeechRecognitionAlternative', +'SpeechTranscription', +'SpeechTranscriptionConfig', +'TextAnnotation', +'TextDetectionConfig', +'TextFrame', +'TextSegment', +'TimestampedObject', +'Track', +'VideoAnnotationProgress', +'VideoAnnotationResults', +'VideoContext', +'VideoIntelligenceServiceClient', +'VideoSegment', +'WordInfo', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json new file mode 100644 index 00000000..016f216f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.videointelligence_v1", + "protoPackage": "google.cloud.videointelligence.v1", + "schema": "1.0", + "services": { + "VideoIntelligenceService": { + "clients": { + "grpc": { + "libraryClient": "VideoIntelligenceServiceClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VideoIntelligenceServiceAsyncClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed b/owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py new file mode 100644 index 00000000..4094cd26 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VideoIntelligenceServiceClient +from .async_client import VideoIntelligenceServiceAsyncClient + +__all__ = ( + 'VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py new file mode 100644 index 00000000..671f6800 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport +from .client import VideoIntelligenceServiceClient + + +class VideoIntelligenceServiceAsyncClient: + """Service that implements the Video Intelligence API.""" + + _client: VideoIntelligenceServiceClient + + DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) + parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) + common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) + parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VideoIntelligenceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def annotate_video(self, + request: video_intelligence.AnnotateVideoRequest = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (:class:`google.cloud.videointelligence_v1.types.AnnotateVideoRequest`): + The request object. Video annotation request. + input_uri (:class:`str`): + Input video location. Currently, only `Cloud + Storage `__ URIs are + supported. URIs must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + To identify multiple videos, a video URI may include + wildcards in the ``object-id``. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + must be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (:class:`Sequence[google.cloud.videointelligence_v1.types.Feature]`): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = video_intelligence.AnnotateVideoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features: + request.features.extend(features) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py new file mode 100644 index 00000000..88cb9ef0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VideoIntelligenceServiceGrpcTransport +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +class VideoIntelligenceServiceClientMeta(type): + """Metaclass for the VideoIntelligenceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] + _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VideoIntelligenceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): + """Service that implements the Video Intelligence API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "videointelligence.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VideoIntelligenceServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VideoIntelligenceServiceTransport): + # transport is a VideoIntelligenceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def annotate_video(self, + request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (Union[google.cloud.videointelligence_v1.types.AnnotateVideoRequest, dict]): + The request object. Video annotation request. + input_uri (str): + Input video location. Currently, only `Cloud + Storage `__ URIs are + supported. URIs must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + To identify multiple videos, a video URI may include + wildcards in the ``object-id``. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + must be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (Sequence[google.cloud.videointelligence_v1.types.Feature]): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a video_intelligence.AnnotateVideoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, video_intelligence.AnnotateVideoRequest): + request = video_intelligence.AnnotateVideoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features is not None: + request.features = features + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.annotate_video] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py new file mode 100644 index 00000000..ef66f264 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VideoIntelligenceServiceTransport +from .grpc import VideoIntelligenceServiceGrpcTransport +from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] +_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport + +__all__ = ( + 'VideoIntelligenceServiceTransport', + 'VideoIntelligenceServiceGrpcTransport', + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py new file mode 100644 index 00000000..efdf98ee --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-videointelligence', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class VideoIntelligenceServiceTransport(abc.ABC): + """Abstract transport class for VideoIntelligenceService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'videointelligence.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.annotate_video: gapic_v1.method.wrap_method( + self.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VideoIntelligenceServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py new file mode 100644 index 00000000..ecef4959 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.videointelligence_v1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO + + +class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): + """gRPC backend transport for VideoIntelligenceService. + + Service that implements the Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + operations_pb2.Operation]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VideoIntelligenceServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..cdc09adc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.videointelligence_v1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import VideoIntelligenceServiceGrpcTransport + + +class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): + """gRPC AsyncIO backend transport for VideoIntelligenceService. + + Service that implements the Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py new file mode 100644 index 00000000..597262b1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py @@ -0,0 +1,112 @@ +# -*- 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 .video_intelligence import ( + AnnotateVideoProgress, + AnnotateVideoRequest, + AnnotateVideoResponse, + DetectedAttribute, + DetectedLandmark, + Entity, + ExplicitContentAnnotation, + ExplicitContentDetectionConfig, + ExplicitContentFrame, + FaceAnnotation, + FaceDetectionAnnotation, + FaceDetectionConfig, + FaceFrame, + FaceSegment, + LabelAnnotation, + LabelDetectionConfig, + LabelFrame, + LabelSegment, + LogoRecognitionAnnotation, + NormalizedBoundingBox, + NormalizedBoundingPoly, + NormalizedVertex, + ObjectTrackingAnnotation, + ObjectTrackingConfig, + ObjectTrackingFrame, + PersonDetectionAnnotation, + PersonDetectionConfig, + ShotChangeDetectionConfig, + SpeechContext, + SpeechRecognitionAlternative, + SpeechTranscription, + SpeechTranscriptionConfig, + TextAnnotation, + TextDetectionConfig, + TextFrame, + TextSegment, + TimestampedObject, + Track, + VideoAnnotationProgress, + VideoAnnotationResults, + VideoContext, + VideoSegment, + WordInfo, + Feature, + LabelDetectionMode, + Likelihood, +) + +__all__ = ( + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'DetectedAttribute', + 'DetectedLandmark', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'FaceAnnotation', + 'FaceDetectionAnnotation', + 'FaceDetectionConfig', + 'FaceFrame', + 'FaceSegment', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'LogoRecognitionAnnotation', + 'NormalizedBoundingBox', + 'NormalizedBoundingPoly', + 'NormalizedVertex', + 'ObjectTrackingAnnotation', + 'ObjectTrackingConfig', + 'ObjectTrackingFrame', + 'PersonDetectionAnnotation', + 'PersonDetectionConfig', + 'ShotChangeDetectionConfig', + 'SpeechContext', + 'SpeechRecognitionAlternative', + 'SpeechTranscription', + 'SpeechTranscriptionConfig', + 'TextAnnotation', + 'TextDetectionConfig', + 'TextFrame', + 'TextSegment', + 'TimestampedObject', + 'Track', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'WordInfo', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py new file mode 100644 index 00000000..e4fb5f23 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py @@ -0,0 +1,1689 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.videointelligence.v1', + manifest={ + 'Feature', + 'LabelDetectionMode', + 'Likelihood', + 'AnnotateVideoRequest', + 'VideoContext', + 'LabelDetectionConfig', + 'ShotChangeDetectionConfig', + 'ObjectTrackingConfig', + 'FaceDetectionConfig', + 'PersonDetectionConfig', + 'ExplicitContentDetectionConfig', + 'TextDetectionConfig', + 'VideoSegment', + 'LabelSegment', + 'LabelFrame', + 'Entity', + 'LabelAnnotation', + 'ExplicitContentFrame', + 'ExplicitContentAnnotation', + 'NormalizedBoundingBox', + 'FaceDetectionAnnotation', + 'PersonDetectionAnnotation', + 'FaceSegment', + 'FaceFrame', + 'FaceAnnotation', + 'TimestampedObject', + 'Track', + 'DetectedAttribute', + 'DetectedLandmark', + 'VideoAnnotationResults', + 'AnnotateVideoResponse', + 'VideoAnnotationProgress', + 'AnnotateVideoProgress', + 'SpeechTranscriptionConfig', + 'SpeechContext', + 'SpeechTranscription', + 'SpeechRecognitionAlternative', + 'WordInfo', + 'NormalizedVertex', + 'NormalizedBoundingPoly', + 'TextSegment', + 'TextFrame', + 'TextAnnotation', + 'ObjectTrackingFrame', + 'ObjectTrackingAnnotation', + 'LogoRecognitionAnnotation', + }, +) + + +class Feature(proto.Enum): + r"""Video annotation feature.""" + FEATURE_UNSPECIFIED = 0 + LABEL_DETECTION = 1 + SHOT_CHANGE_DETECTION = 2 + EXPLICIT_CONTENT_DETECTION = 3 + FACE_DETECTION = 4 + SPEECH_TRANSCRIPTION = 6 + TEXT_DETECTION = 7 + OBJECT_TRACKING = 9 + LOGO_RECOGNITION = 12 + PERSON_DETECTION = 14 + + +class LabelDetectionMode(proto.Enum): + r"""Label detection mode.""" + LABEL_DETECTION_MODE_UNSPECIFIED = 0 + SHOT_MODE = 1 + FRAME_MODE = 2 + SHOT_AND_FRAME_MODE = 3 + + +class Likelihood(proto.Enum): + r"""Bucketized representation of likelihood.""" + LIKELIHOOD_UNSPECIFIED = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class AnnotateVideoRequest(proto.Message): + r"""Video annotation request. + + Attributes: + input_uri (str): + Input video location. Currently, only `Cloud + Storage `__ URIs are + supported. URIs must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + To identify multiple videos, a video URI may include + wildcards in the ``object-id``. Supported wildcards: '*' to + match 0 or more characters; '?' to match 1 character. If + unset, the input video should be embedded in the request as + ``input_content``. If set, ``input_content`` must be unset. + input_content (bytes): + The video data bytes. If unset, the input video(s) should be + specified via the ``input_uri``. If set, ``input_uri`` must + be unset. + features (Sequence[google.cloud.videointelligence_v1.types.Feature]): + Required. Requested video annotation + features. + video_context (google.cloud.videointelligence_v1.types.VideoContext): + Additional video context and/or feature- + pecific parameters. + output_uri (str): + Optional. Location where the output (in JSON format) should + be stored. Currently, only `Cloud + Storage `__ URIs are + supported. These must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + location_id (str): + Optional. Cloud region where annotation should take place. + Supported cloud regions are: ``us-east1``, ``us-west1``, + ``europe-west1``, ``asia-east1``. If no region is specified, + the region will be determined based on video file location. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + input_content = proto.Field( + proto.BYTES, + number=6, + ) + features = proto.RepeatedField( + proto.ENUM, + number=2, + enum='Feature', + ) + video_context = proto.Field( + proto.MESSAGE, + number=3, + message='VideoContext', + ) + output_uri = proto.Field( + proto.STRING, + number=4, + ) + location_id = proto.Field( + proto.STRING, + number=5, + ) + + +class VideoContext(proto.Message): + r"""Video context and/or feature-specific parameters. + + Attributes: + segments (Sequence[google.cloud.videointelligence_v1.types.VideoSegment]): + Video segments to annotate. The segments may + overlap and are not required to be contiguous or + span the whole video. If unspecified, each video + is treated as a single segment. + label_detection_config (google.cloud.videointelligence_v1.types.LabelDetectionConfig): + Config for LABEL_DETECTION. + shot_change_detection_config (google.cloud.videointelligence_v1.types.ShotChangeDetectionConfig): + Config for SHOT_CHANGE_DETECTION. + explicit_content_detection_config (google.cloud.videointelligence_v1.types.ExplicitContentDetectionConfig): + Config for EXPLICIT_CONTENT_DETECTION. + face_detection_config (google.cloud.videointelligence_v1.types.FaceDetectionConfig): + Config for FACE_DETECTION. + speech_transcription_config (google.cloud.videointelligence_v1.types.SpeechTranscriptionConfig): + Config for SPEECH_TRANSCRIPTION. + text_detection_config (google.cloud.videointelligence_v1.types.TextDetectionConfig): + Config for TEXT_DETECTION. + person_detection_config (google.cloud.videointelligence_v1.types.PersonDetectionConfig): + Config for PERSON_DETECTION. + object_tracking_config (google.cloud.videointelligence_v1.types.ObjectTrackingConfig): + Config for OBJECT_TRACKING. + """ + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + label_detection_config = proto.Field( + proto.MESSAGE, + number=2, + message='LabelDetectionConfig', + ) + shot_change_detection_config = proto.Field( + proto.MESSAGE, + number=3, + message='ShotChangeDetectionConfig', + ) + explicit_content_detection_config = proto.Field( + proto.MESSAGE, + number=4, + message='ExplicitContentDetectionConfig', + ) + face_detection_config = proto.Field( + proto.MESSAGE, + number=5, + message='FaceDetectionConfig', + ) + speech_transcription_config = proto.Field( + proto.MESSAGE, + number=6, + message='SpeechTranscriptionConfig', + ) + text_detection_config = proto.Field( + proto.MESSAGE, + number=8, + message='TextDetectionConfig', + ) + person_detection_config = proto.Field( + proto.MESSAGE, + number=11, + message='PersonDetectionConfig', + ) + object_tracking_config = proto.Field( + proto.MESSAGE, + number=13, + message='ObjectTrackingConfig', + ) + + +class LabelDetectionConfig(proto.Message): + r"""Config for LABEL_DETECTION. + + Attributes: + label_detection_mode (google.cloud.videointelligence_v1.types.LabelDetectionMode): + What labels should be detected with LABEL_DETECTION, in + addition to video-level labels or segment-level labels. If + unspecified, defaults to ``SHOT_MODE``. + stationary_camera (bool): + Whether the video has been shot from a stationary (i.e., + non-moving) camera. When set to true, might improve + detection accuracy for moving objects. Should be used with + ``SHOT_AND_FRAME_MODE`` enabled. + model (str): + Model to use for label detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + frame_confidence_threshold (float): + The confidence threshold we perform filtering on the labels + from frame-level detection. If not set, it is set to 0.4 by + default. The valid range for this threshold is [0.1, 0.9]. + Any value set outside of this range will be clipped. Note: + For best results, follow the default threshold. We will + update the default threshold everytime when we release a new + model. + video_confidence_threshold (float): + The confidence threshold we perform filtering on the labels + from video-level and shot-level detections. If not set, it's + set to 0.3 by default. The valid range for this threshold is + [0.1, 0.9]. Any value set outside of this range will be + clipped. Note: For best results, follow the default + threshold. We will update the default threshold everytime + when we release a new model. + """ + + label_detection_mode = proto.Field( + proto.ENUM, + number=1, + enum='LabelDetectionMode', + ) + stationary_camera = proto.Field( + proto.BOOL, + number=2, + ) + model = proto.Field( + proto.STRING, + number=3, + ) + frame_confidence_threshold = proto.Field( + proto.FLOAT, + number=4, + ) + video_confidence_threshold = proto.Field( + proto.FLOAT, + number=5, + ) + + +class ShotChangeDetectionConfig(proto.Message): + r"""Config for SHOT_CHANGE_DETECTION. + + Attributes: + model (str): + Model to use for shot change detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class ObjectTrackingConfig(proto.Message): + r"""Config for OBJECT_TRACKING. + + Attributes: + model (str): + Model to use for object tracking. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class FaceDetectionConfig(proto.Message): + r"""Config for FACE_DETECTION. + + Attributes: + model (str): + Model to use for face detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + include_bounding_boxes (bool): + Whether bounding boxes are included in the + face annotation output. + include_attributes (bool): + Whether to enable face attributes detection, such as + glasses, dark_glasses, mouth_open etc. Ignored if + 'include_bounding_boxes' is set to false. + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + include_bounding_boxes = proto.Field( + proto.BOOL, + number=2, + ) + include_attributes = proto.Field( + proto.BOOL, + number=5, + ) + + +class PersonDetectionConfig(proto.Message): + r"""Config for PERSON_DETECTION. + + Attributes: + include_bounding_boxes (bool): + Whether bounding boxes are included in the + person detection annotation output. + include_pose_landmarks (bool): + Whether to enable pose landmarks detection. Ignored if + 'include_bounding_boxes' is set to false. + include_attributes (bool): + Whether to enable person attributes detection, such as cloth + color (black, blue, etc), type (coat, dress, etc), pattern + (plain, floral, etc), hair, etc. Ignored if + 'include_bounding_boxes' is set to false. + """ + + include_bounding_boxes = proto.Field( + proto.BOOL, + number=1, + ) + include_pose_landmarks = proto.Field( + proto.BOOL, + number=2, + ) + include_attributes = proto.Field( + proto.BOOL, + number=3, + ) + + +class ExplicitContentDetectionConfig(proto.Message): + r"""Config for EXPLICIT_CONTENT_DETECTION. + + Attributes: + model (str): + Model to use for explicit content detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class TextDetectionConfig(proto.Message): + r"""Config for TEXT_DETECTION. + + Attributes: + language_hints (Sequence[str]): + Language hint can be specified if the + language to be detected is known a priori. It + can increase the accuracy of the detection. + Language hint must be language code in BCP-47 + format. + + Automatic language detection is performed if no + hint is provided. + model (str): + Model to use for text detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + language_hints = proto.RepeatedField( + proto.STRING, + number=1, + ) + model = proto.Field( + proto.STRING, + number=2, + ) + + +class VideoSegment(proto.Message): + r"""Video segment. + + Attributes: + start_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the start of the segment + (inclusive). + end_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the end of the segment + (inclusive). + """ + + start_time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class LabelSegment(proto.Message): + r"""Video segment level annotation results for label detection. + + Attributes: + segment (google.cloud.videointelligence_v1.types.VideoSegment): + Video segment where a label was detected. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class LabelFrame(proto.Message): + r"""Video frame level annotation results for label detection. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class Entity(proto.Message): + r"""Detected entity from video analysis. + + Attributes: + entity_id (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + description (str): + Textual description, e.g., ``Fixed-gear bicycle``. + language_code (str): + Language code for ``description`` in BCP-47 format. + """ + + entity_id = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class LabelAnnotation(proto.Message): + r"""Label annotation. + + Attributes: + entity (google.cloud.videointelligence_v1.types.Entity): + Detected entity. + category_entities (Sequence[google.cloud.videointelligence_v1.types.Entity]): + Common categories for the detected entity. For example, when + the label is ``Terrier``, the category is likely ``dog``. + And in some cases there might be more than one categories + e.g., ``Terrier`` could also be a ``pet``. + segments (Sequence[google.cloud.videointelligence_v1.types.LabelSegment]): + All video segments where a label was + detected. + frames (Sequence[google.cloud.videointelligence_v1.types.LabelFrame]): + All video frames where a label was detected. + version (str): + Feature version. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + category_entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Entity', + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelSegment', + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelFrame', + ) + version = proto.Field( + proto.STRING, + number=5, + ) + + +class ExplicitContentFrame(proto.Message): + r"""Video frame level annotation results for explicit content. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + pornography_likelihood (google.cloud.videointelligence_v1.types.Likelihood): + Likelihood of the pornography content.. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + pornography_likelihood = proto.Field( + proto.ENUM, + number=2, + enum='Likelihood', + ) + + +class ExplicitContentAnnotation(proto.Message): + r"""Explicit content annotation (based on per-frame visual + signals only). If no explicit content has been detected in a + frame, no annotations are present for that frame. + + Attributes: + frames (Sequence[google.cloud.videointelligence_v1.types.ExplicitContentFrame]): + All video frames where explicit content was + detected. + version (str): + Feature version. + """ + + frames = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExplicitContentFrame', + ) + version = proto.Field( + proto.STRING, + number=2, + ) + + +class NormalizedBoundingBox(proto.Message): + r"""Normalized bounding box. The normalized vertex coordinates are + relative to the original image. Range: [0, 1]. + + Attributes: + left (float): + Left X coordinate. + top (float): + Top Y coordinate. + right (float): + Right X coordinate. + bottom (float): + Bottom Y coordinate. + """ + + left = proto.Field( + proto.FLOAT, + number=1, + ) + top = proto.Field( + proto.FLOAT, + number=2, + ) + right = proto.Field( + proto.FLOAT, + number=3, + ) + bottom = proto.Field( + proto.FLOAT, + number=4, + ) + + +class FaceDetectionAnnotation(proto.Message): + r"""Face detection annotation. + + Attributes: + tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): + The face tracks with attributes. + thumbnail (bytes): + The thumbnail of a person's face. + version (str): + Feature version. + """ + + tracks = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Track', + ) + thumbnail = proto.Field( + proto.BYTES, + number=4, + ) + version = proto.Field( + proto.STRING, + number=5, + ) + + +class PersonDetectionAnnotation(proto.Message): + r"""Person detection annotation per video. + + Attributes: + tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): + The detected tracks of a person. + version (str): + Feature version. + """ + + tracks = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Track', + ) + version = proto.Field( + proto.STRING, + number=2, + ) + + +class FaceSegment(proto.Message): + r"""Video segment level annotation results for face detection. + + Attributes: + segment (google.cloud.videointelligence_v1.types.VideoSegment): + Video segment where a face was detected. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + + +class FaceFrame(proto.Message): + r"""Deprecated. No effect. + + Attributes: + normalized_bounding_boxes (Sequence[google.cloud.videointelligence_v1.types.NormalizedBoundingBox]): + Normalized Bounding boxes in a frame. + There can be more than one boxes if the same + face is detected in multiple locations within + the current frame. + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + """ + + normalized_bounding_boxes = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedBoundingBox', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class FaceAnnotation(proto.Message): + r"""Deprecated. No effect. + + Attributes: + thumbnail (bytes): + Thumbnail of a representative face view (in + JPEG format). + segments (Sequence[google.cloud.videointelligence_v1.types.FaceSegment]): + All video segments where a face was detected. + frames (Sequence[google.cloud.videointelligence_v1.types.FaceFrame]): + All video frames where a face was detected. + """ + + thumbnail = proto.Field( + proto.BYTES, + number=1, + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='FaceSegment', + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='FaceFrame', + ) + + +class TimestampedObject(proto.Message): + r"""For tracking related features. An object at time_offset with + attributes, and located with normalized_bounding_box. + + Attributes: + normalized_bounding_box (google.cloud.videointelligence_v1.types.NormalizedBoundingBox): + Normalized Bounding box in a frame, where the + object is located. + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + object. + attributes (Sequence[google.cloud.videointelligence_v1.types.DetectedAttribute]): + Optional. The attributes of the object in the + bounding box. + landmarks (Sequence[google.cloud.videointelligence_v1.types.DetectedLandmark]): + Optional. The detected landmarks. + """ + + normalized_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingBox', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + attributes = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='DetectedAttribute', + ) + landmarks = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='DetectedLandmark', + ) + + +class Track(proto.Message): + r"""A track of an object instance. + + Attributes: + segment (google.cloud.videointelligence_v1.types.VideoSegment): + Video segment of a track. + timestamped_objects (Sequence[google.cloud.videointelligence_v1.types.TimestampedObject]): + The object with timestamp and attributes per + frame in the track. + attributes (Sequence[google.cloud.videointelligence_v1.types.DetectedAttribute]): + Optional. Attributes in the track level. + confidence (float): + Optional. The confidence score of the tracked + object. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + timestamped_objects = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TimestampedObject', + ) + attributes = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='DetectedAttribute', + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + +class DetectedAttribute(proto.Message): + r"""A generic detected attribute represented by name in string + format. + + Attributes: + name (str): + The name of the attribute, for example, glasses, + dark_glasses, mouth_open. A full list of supported type + names will be provided in the document. + confidence (float): + Detected attribute confidence. Range [0, 1]. + value (str): + Text value of the detection result. For + example, the value for "HairColor" can be + "black", "blonde", etc. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + value = proto.Field( + proto.STRING, + number=3, + ) + + +class DetectedLandmark(proto.Message): + r"""A generic detected landmark represented by name in string + format and a 2D location. + + Attributes: + name (str): + The name of this landmark, for example, left_hand, + right_shoulder. + point (google.cloud.videointelligence_v1.types.NormalizedVertex): + The 2D point of the detected landmark using + the normalized image coordindate system. The + normalized coordinates have the range from 0 to + 1. + confidence (float): + The confidence score of the detected landmark. Range [0, 1]. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + point = proto.Field( + proto.MESSAGE, + number=2, + message='NormalizedVertex', + ) + confidence = proto.Field( + proto.FLOAT, + number=3, + ) + + +class VideoAnnotationResults(proto.Message): + r"""Annotation results for a single video. + + Attributes: + input_uri (str): + Video file location in `Cloud + Storage `__. + segment (google.cloud.videointelligence_v1.types.VideoSegment): + Video segment on which the annotation is run. + segment_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): + Topical label annotations on video level or + user-specified segment level. There is exactly + one element for each unique label. + segment_presence_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): + Presence label annotations on video level or user-specified + segment level. There is exactly one element for each unique + label. Compared to the existing topical + ``segment_label_annotations``, this field presents more + fine-grained, segment-level labels detected in video content + and is made available only when the client sets + ``LabelDetectionConfig.model`` to "builtin/latest" in the + request. + shot_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): + Topical label annotations on shot level. + There is exactly one element for each unique + label. + shot_presence_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): + Presence label annotations on shot level. There is exactly + one element for each unique label. Compared to the existing + topical ``shot_label_annotations``, this field presents more + fine-grained, shot-level labels detected in video content + and is made available only when the client sets + ``LabelDetectionConfig.model`` to "builtin/latest" in the + request. + frame_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): + Label annotations on frame level. + There is exactly one element for each unique + label. + face_annotations (Sequence[google.cloud.videointelligence_v1.types.FaceAnnotation]): + Deprecated. Please use ``face_detection_annotations`` + instead. + face_detection_annotations (Sequence[google.cloud.videointelligence_v1.types.FaceDetectionAnnotation]): + Face detection annotations. + shot_annotations (Sequence[google.cloud.videointelligence_v1.types.VideoSegment]): + Shot annotations. Each shot is represented as + a video segment. + explicit_annotation (google.cloud.videointelligence_v1.types.ExplicitContentAnnotation): + Explicit content annotation. + speech_transcriptions (Sequence[google.cloud.videointelligence_v1.types.SpeechTranscription]): + Speech transcription. + text_annotations (Sequence[google.cloud.videointelligence_v1.types.TextAnnotation]): + OCR text detection and tracking. + Annotations for list of detected text snippets. + Each will have list of frame information + associated with it. + object_annotations (Sequence[google.cloud.videointelligence_v1.types.ObjectTrackingAnnotation]): + Annotations for list of objects detected and + tracked in video. + logo_recognition_annotations (Sequence[google.cloud.videointelligence_v1.types.LogoRecognitionAnnotation]): + Annotations for list of logos detected, + tracked and recognized in video. + person_detection_annotations (Sequence[google.cloud.videointelligence_v1.types.PersonDetectionAnnotation]): + Person detection annotations. + error (google.rpc.status_pb2.Status): + If set, indicates an error. Note that for a single + ``AnnotateVideoRequest`` some videos may succeed and some + may fail. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + segment = proto.Field( + proto.MESSAGE, + number=10, + message='VideoSegment', + ) + segment_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='LabelAnnotation', + ) + segment_presence_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=23, + message='LabelAnnotation', + ) + shot_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelAnnotation', + ) + shot_presence_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=24, + message='LabelAnnotation', + ) + frame_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelAnnotation', + ) + face_annotations = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='FaceAnnotation', + ) + face_detection_annotations = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='FaceDetectionAnnotation', + ) + shot_annotations = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='VideoSegment', + ) + explicit_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='ExplicitContentAnnotation', + ) + speech_transcriptions = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='SpeechTranscription', + ) + text_annotations = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='TextAnnotation', + ) + object_annotations = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='ObjectTrackingAnnotation', + ) + logo_recognition_annotations = proto.RepeatedField( + proto.MESSAGE, + number=19, + message='LogoRecognitionAnnotation', + ) + person_detection_annotations = proto.RepeatedField( + proto.MESSAGE, + number=20, + message='PersonDetectionAnnotation', + ) + error = proto.Field( + proto.MESSAGE, + number=9, + message=status_pb2.Status, + ) + + +class AnnotateVideoResponse(proto.Message): + r"""Video annotation response. Included in the ``response`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_results (Sequence[google.cloud.videointelligence_v1.types.VideoAnnotationResults]): + Annotation results for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationResults', + ) + + +class VideoAnnotationProgress(proto.Message): + r"""Annotation progress for a single video. + + Attributes: + input_uri (str): + Video file location in `Cloud + Storage `__. + progress_percent (int): + Approximate percentage processed thus far. + Guaranteed to be 100 when fully processed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent update. + feature (google.cloud.videointelligence_v1.types.Feature): + Specifies which feature is being tracked if + the request contains more than one feature. + segment (google.cloud.videointelligence_v1.types.VideoSegment): + Specifies which segment is being tracked if + the request contains more than one segment. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + progress_percent = proto.Field( + proto.INT32, + number=2, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + feature = proto.Field( + proto.ENUM, + number=5, + enum='Feature', + ) + segment = proto.Field( + proto.MESSAGE, + number=6, + message='VideoSegment', + ) + + +class AnnotateVideoProgress(proto.Message): + r"""Video annotation progress. Included in the ``metadata`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_progress (Sequence[google.cloud.videointelligence_v1.types.VideoAnnotationProgress]): + Progress metadata for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_progress = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationProgress', + ) + + +class SpeechTranscriptionConfig(proto.Message): + r"""Config for SPEECH_TRANSCRIPTION. + + Attributes: + language_code (str): + Required. *Required* The language of the supplied audio as a + `BCP-47 `__ + language tag. Example: "en-US". See `Language + Support `__ + for a list of the currently supported language codes. + max_alternatives (int): + Optional. Maximum number of recognition hypotheses to be + returned. Specifically, the maximum number of + ``SpeechRecognitionAlternative`` messages within each + ``SpeechTranscription``. The server may return fewer than + ``max_alternatives``. Valid values are ``0``-``30``. A value + of ``0`` or ``1`` will return a maximum of one. If omitted, + will return a maximum of one. + filter_profanity (bool): + Optional. If set to ``true``, the server will attempt to + filter out profanities, replacing all but the initial + character in each filtered word with asterisks, e.g. "f***". + If set to ``false`` or omitted, profanities won't be + filtered out. + speech_contexts (Sequence[google.cloud.videointelligence_v1.types.SpeechContext]): + Optional. A means to provide context to + assist the speech recognition. + enable_automatic_punctuation (bool): + Optional. If 'true', adds punctuation to + recognition result hypotheses. This feature is + only available in select languages. Setting this + for requests in other languages has no effect at + all. The default 'false' value does not add + punctuation to result hypotheses. NOTE: "This is + currently offered as an experimental service, + complimentary to all users. In the future this + may be exclusively available as a premium + feature.". + audio_tracks (Sequence[int]): + Optional. For file formats, such as MXF or + MKV, supporting multiple audio tracks, specify + up to two tracks. Default: track 0. + enable_speaker_diarization (bool): + Optional. If 'true', enables speaker detection for each + recognized word in the top alternative of the recognition + result using a speaker_tag provided in the WordInfo. Note: + When this is true, we send all the words from the beginning + of the audio for the top alternative in every consecutive + response. This is done in order to improve our speaker tags + as our models learn to identify the speakers in the + conversation over time. + diarization_speaker_count (int): + Optional. If set, specifies the estimated number of speakers + in the conversation. If not set, defaults to '2'. Ignored + unless enable_speaker_diarization is set to true. + enable_word_confidence (bool): + Optional. If ``true``, the top result includes a list of + words and the confidence for those words. If ``false``, no + word-level confidence information is returned. The default + is ``false``. + """ + + language_code = proto.Field( + proto.STRING, + number=1, + ) + max_alternatives = proto.Field( + proto.INT32, + number=2, + ) + filter_profanity = proto.Field( + proto.BOOL, + number=3, + ) + speech_contexts = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SpeechContext', + ) + enable_automatic_punctuation = proto.Field( + proto.BOOL, + number=5, + ) + audio_tracks = proto.RepeatedField( + proto.INT32, + number=6, + ) + enable_speaker_diarization = proto.Field( + proto.BOOL, + number=7, + ) + diarization_speaker_count = proto.Field( + proto.INT32, + number=8, + ) + enable_word_confidence = proto.Field( + proto.BOOL, + number=9, + ) + + +class SpeechContext(proto.Message): + r"""Provides "hints" to the speech recognizer to favor specific + words and phrases in the results. + + Attributes: + phrases (Sequence[str]): + Optional. A list of strings containing words and phrases + "hints" so that the speech recognition is more likely to + recognize them. This can be used to improve the accuracy for + specific words and phrases, for example, if specific + commands are typically spoken by the user. This can also be + used to add additional words to the vocabulary of the + recognizer. See `usage + limits `__. + """ + + phrases = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class SpeechTranscription(proto.Message): + r"""A speech recognition result corresponding to a portion of the + audio. + + Attributes: + alternatives (Sequence[google.cloud.videointelligence_v1.types.SpeechRecognitionAlternative]): + May contain one or more recognition hypotheses (up to the + maximum specified in ``max_alternatives``). These + alternatives are ordered in terms of accuracy, with the top + (first) alternative being the most probable, as ranked by + the recognizer. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SpeechRecognitionAlternative', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class SpeechRecognitionAlternative(proto.Message): + r"""Alternative hypotheses (a.k.a. n-best list). + + Attributes: + transcript (str): + Transcript text representing the words that + the user spoke. + confidence (float): + Output only. The confidence estimate between 0.0 and 1.0. A + higher number indicates an estimated greater likelihood that + the recognized words are correct. This field is set only for + the top alternative. This field is not guaranteed to be + accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + words (Sequence[google.cloud.videointelligence_v1.types.WordInfo]): + Output only. A list of word-specific information for each + recognized word. Note: When ``enable_speaker_diarization`` + is set to true, you will see all the words from the + beginning of the audio. + """ + + transcript = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + words = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='WordInfo', + ) + + +class WordInfo(proto.Message): + r"""Word-specific information for recognized words. Word information is + only included in the response when certain request parameters are + set, such as ``enable_word_time_offsets``. + + Attributes: + start_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the start of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + end_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the end of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + word (str): + The word corresponding to this set of + information. + confidence (float): + Output only. The confidence estimate between 0.0 and 1.0. A + higher number indicates an estimated greater likelihood that + the recognized words are correct. This field is set only for + the top alternative. This field is not guaranteed to be + accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + speaker_tag (int): + Output only. A distinct integer value is assigned for every + speaker within the audio. This field specifies which one of + those speakers was detected to have spoken this word. Value + ranges from 1 up to diarization_speaker_count, and is only + set if speaker diarization is enabled. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + word = proto.Field( + proto.STRING, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + speaker_tag = proto.Field( + proto.INT32, + number=5, + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field( + proto.FLOAT, + number=1, + ) + y = proto.Field( + proto.FLOAT, + number=2, + ) + + +class NormalizedBoundingPoly(proto.Message): + r"""Normalized bounding polygon for text (that might not be aligned with + axis). Contains list of the corner points in clockwise order + starting from top-left corner. For example, for a rectangular + bounding box: When the text is horizontal it might look like: 0----1 + \| \| 3----2 + + When it's clockwise rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 + + and the vertex order will still be (0, 1, 2, 3). Note that values + can be less than 0, or greater than 1 due to trignometric + calculations for location of the box. + + Attributes: + vertices (Sequence[google.cloud.videointelligence_v1.types.NormalizedVertex]): + Normalized vertices of the bounding polygon. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class TextSegment(proto.Message): + r"""Video segment level annotation results for text detection. + + Attributes: + segment (google.cloud.videointelligence_v1.types.VideoSegment): + Video segment where a text snippet was + detected. + confidence (float): + Confidence for the track of detected text. It + is calculated as the highest over all frames + where OCR detected text appears. + frames (Sequence[google.cloud.videointelligence_v1.types.TextFrame]): + Information related to the frames where OCR + detected text appears. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='TextFrame', + ) + + +class TextFrame(proto.Message): + r"""Video frame level annotation results for text annotation + (OCR). Contains information regarding timestamp and bounding box + locations for the frames containing detected OCR text snippets. + + Attributes: + rotated_bounding_box (google.cloud.videointelligence_v1.types.NormalizedBoundingPoly): + Bounding polygon of the detected text for + this frame. + time_offset (google.protobuf.duration_pb2.Duration): + Timestamp of this frame. + """ + + rotated_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingPoly', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class TextAnnotation(proto.Message): + r"""Annotations related to one detected OCR text snippet. This + will contain the corresponding text, confidence value, and frame + level information for each detection. + + Attributes: + text (str): + The detected text. + segments (Sequence[google.cloud.videointelligence_v1.types.TextSegment]): + All video segments where OCR detected text + appears. + version (str): + Feature version. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TextSegment', + ) + version = proto.Field( + proto.STRING, + number=3, + ) + + +class ObjectTrackingFrame(proto.Message): + r"""Video frame level annotations for object detection and + tracking. This field stores per frame location, time offset, and + confidence. + + Attributes: + normalized_bounding_box (google.cloud.videointelligence_v1.types.NormalizedBoundingBox): + The normalized bounding box location of this + object track for the frame. + time_offset (google.protobuf.duration_pb2.Duration): + The timestamp of the frame in microseconds. + """ + + normalized_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingBox', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ObjectTrackingAnnotation(proto.Message): + r"""Annotations corresponding to one tracked object. + + Attributes: + segment (google.cloud.videointelligence_v1.types.VideoSegment): + Non-streaming batch mode ONLY. + Each object track corresponds to one video + segment where it appears. + track_id (int): + Streaming mode ONLY. In streaming mode, we do not know the + end time of a tracked object before it is completed. Hence, + there is no VideoSegment info returned. Instead, we provide + a unique identifiable integer track_id so that the customers + can correlate the results of the ongoing + ObjectTrackAnnotation of the same track_id over time. + entity (google.cloud.videointelligence_v1.types.Entity): + Entity to specify the object category that + this track is labeled as. + confidence (float): + Object category's labeling confidence of this + track. + frames (Sequence[google.cloud.videointelligence_v1.types.ObjectTrackingFrame]): + Information corresponding to all frames where + this object track appears. Non-streaming batch + mode: it may be one or multiple + ObjectTrackingFrame messages in frames. + Streaming mode: it can only be one + ObjectTrackingFrame message in frames. + version (str): + Feature version. + """ + + segment = proto.Field( + proto.MESSAGE, + number=3, + oneof='track_info', + message='VideoSegment', + ) + track_id = proto.Field( + proto.INT64, + number=5, + oneof='track_info', + ) + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ObjectTrackingFrame', + ) + version = proto.Field( + proto.STRING, + number=6, + ) + + +class LogoRecognitionAnnotation(proto.Message): + r"""Annotation corresponding to one detected, tracked and + recognized logo class. + + Attributes: + entity (google.cloud.videointelligence_v1.types.Entity): + Entity category information to specify the + logo class that all the logo tracks within this + LogoRecognitionAnnotation are recognized as. + tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): + All logo tracks where the recognized logo + appears. Each track corresponds to one logo + instance appearing in consecutive frames. + segments (Sequence[google.cloud.videointelligence_v1.types.VideoSegment]): + All video segments where the recognized logo + appears. There might be multiple instances of + the same logo class appearing in one + VideoSegment. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + tracks = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Track', + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='VideoSegment', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 00000000..6a8f2d45 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/videointelligence_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py new file mode 100644 index 00000000..7c1a29e9 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class videointelligenceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=videointelligenceCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the videointelligence client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 00000000..87b7ba3d --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-videointelligence', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py b/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py new file mode 100644 index 00000000..45358458 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py @@ -0,0 +1,1177 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.videointelligence_v1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient +from google.cloud.videointelligence_v1.services.video_intelligence_service import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1.services.video_intelligence_service import transports +from google.cloud.videointelligence_v1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.videointelligence_v1.types import video_intelligence +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_client_get_transport_class(): + transport = VideoIntelligenceServiceClient.get_transport_class() + available_transports = [ + transports.VideoIntelligenceServiceGrpcTransport, + ] + assert transport in available_transports + + transport = VideoIntelligenceServiceClient.get_transport_class("grpc") + assert transport == transports.VideoIntelligenceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_video_intelligence_service_client_client_options_from_dict(): + with mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VideoIntelligenceServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_annotate_video_from_dict(): + test_annotate_video(request_type=dict) + + +def test_annotate_video_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + client.annotate_video() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + +@pytest.mark.asyncio +async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_annotate_video_async_from_dict(): + await test_annotate_video_async(request_type=dict) + + +def test_annotate_video_flattened(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +def test_annotate_video_flattened_error(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_error_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VideoIntelligenceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VideoIntelligenceServiceGrpcTransport, + ) + +def test_video_intelligence_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_video_intelligence_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'annotate_video', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_video_intelligence_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "videointelligence.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="videointelligence.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_video_intelligence_service_host_no_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_host_with_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:8000' + +def test_video_intelligence_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_video_intelligence_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_video_intelligence_service_grpc_lro_client(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_video_intelligence_service_grpc_lro_async_client(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = VideoIntelligenceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = VideoIntelligenceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VideoIntelligenceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = VideoIntelligenceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = VideoIntelligenceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = VideoIntelligenceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VideoIntelligenceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = VideoIntelligenceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = VideoIntelligenceServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1beta2/.coveragerc b/owl-bot-staging/v1beta2/.coveragerc new file mode 100644 index 00000000..45c608f8 --- /dev/null +++ b/owl-bot-staging/v1beta2/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/videointelligence/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta2/MANIFEST.in b/owl-bot-staging/v1beta2/MANIFEST.in new file mode 100644 index 00000000..a12cb4f4 --- /dev/null +++ b/owl-bot-staging/v1beta2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/videointelligence *.py +recursive-include google/cloud/videointelligence_v1beta2 *.py diff --git a/owl-bot-staging/v1beta2/README.rst b/owl-bot-staging/v1beta2/README.rst new file mode 100644 index 00000000..bedc3680 --- /dev/null +++ b/owl-bot-staging/v1beta2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Videointelligence API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Videointelligence API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta2/docs/conf.py b/owl-bot-staging/v1beta2/docs/conf.py new file mode 100644 index 00000000..7a82f64b --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-videointelligence documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-videointelligence" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-videointelligence-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-videointelligence.tex", + u"google-cloud-videointelligence Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-videointelligence", + u"Google Cloud Videointelligence Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-videointelligence", + u"google-cloud-videointelligence Documentation", + author, + "google-cloud-videointelligence", + "GAPIC library for Google Cloud Videointelligence API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta2/docs/index.rst b/owl-bot-staging/v1beta2/docs/index.rst new file mode 100644 index 00000000..f473cb6a --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + videointelligence_v1beta2/services + videointelligence_v1beta2/types diff --git a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst new file mode 100644 index 00000000..c8f45a1e --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Videointelligence v1beta2 API +======================================================= +.. toctree:: + :maxdepth: 2 + + video_intelligence_service diff --git a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst new file mode 100644 index 00000000..62921eac --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Videointelligence v1beta2 API +==================================================== + +.. automodule:: google.cloud.videointelligence_v1beta2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst new file mode 100644 index 00000000..ab6c31d3 --- /dev/null +++ b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst @@ -0,0 +1,6 @@ +VideoIntelligenceService +------------------------------------------ + +.. automodule:: google.cloud.videointelligence_v1beta2.services.video_intelligence_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py new file mode 100644 index 00000000..d69bd06c --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py @@ -0,0 +1,71 @@ +# -*- 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.videointelligence_v1beta2.services.video_intelligence_service.client import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1beta2.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient + +from google.cloud.videointelligence_v1beta2.types.video_intelligence import AnnotateVideoProgress +from google.cloud.videointelligence_v1beta2.types.video_intelligence import AnnotateVideoRequest +from google.cloud.videointelligence_v1beta2.types.video_intelligence import AnnotateVideoResponse +from google.cloud.videointelligence_v1beta2.types.video_intelligence import Entity +from google.cloud.videointelligence_v1beta2.types.video_intelligence import ExplicitContentAnnotation +from google.cloud.videointelligence_v1beta2.types.video_intelligence import ExplicitContentDetectionConfig +from google.cloud.videointelligence_v1beta2.types.video_intelligence import ExplicitContentFrame +from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceAnnotation +from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceDetectionConfig +from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceFrame +from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceSegment +from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelAnnotation +from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelDetectionConfig +from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelFrame +from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelSegment +from google.cloud.videointelligence_v1beta2.types.video_intelligence import NormalizedBoundingBox +from google.cloud.videointelligence_v1beta2.types.video_intelligence import ShotChangeDetectionConfig +from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoAnnotationProgress +from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoAnnotationResults +from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoContext +from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoSegment +from google.cloud.videointelligence_v1beta2.types.video_intelligence import Feature +from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelDetectionMode +from google.cloud.videointelligence_v1beta2.types.video_intelligence import Likelihood + +__all__ = ('VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'FaceAnnotation', + 'FaceDetectionConfig', + 'FaceFrame', + 'FaceSegment', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'NormalizedBoundingBox', + 'ShotChangeDetectionConfig', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py new file mode 100644 index 00000000..19f1f67d --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.video_intelligence_service import VideoIntelligenceServiceClient +from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient + +from .types.video_intelligence import AnnotateVideoProgress +from .types.video_intelligence import AnnotateVideoRequest +from .types.video_intelligence import AnnotateVideoResponse +from .types.video_intelligence import Entity +from .types.video_intelligence import ExplicitContentAnnotation +from .types.video_intelligence import ExplicitContentDetectionConfig +from .types.video_intelligence import ExplicitContentFrame +from .types.video_intelligence import FaceAnnotation +from .types.video_intelligence import FaceDetectionConfig +from .types.video_intelligence import FaceFrame +from .types.video_intelligence import FaceSegment +from .types.video_intelligence import LabelAnnotation +from .types.video_intelligence import LabelDetectionConfig +from .types.video_intelligence import LabelFrame +from .types.video_intelligence import LabelSegment +from .types.video_intelligence import NormalizedBoundingBox +from .types.video_intelligence import ShotChangeDetectionConfig +from .types.video_intelligence import VideoAnnotationProgress +from .types.video_intelligence import VideoAnnotationResults +from .types.video_intelligence import VideoContext +from .types.video_intelligence import VideoSegment +from .types.video_intelligence import Feature +from .types.video_intelligence import LabelDetectionMode +from .types.video_intelligence import Likelihood + +__all__ = ( + 'VideoIntelligenceServiceAsyncClient', +'AnnotateVideoProgress', +'AnnotateVideoRequest', +'AnnotateVideoResponse', +'Entity', +'ExplicitContentAnnotation', +'ExplicitContentDetectionConfig', +'ExplicitContentFrame', +'FaceAnnotation', +'FaceDetectionConfig', +'FaceFrame', +'FaceSegment', +'Feature', +'LabelAnnotation', +'LabelDetectionConfig', +'LabelDetectionMode', +'LabelFrame', +'LabelSegment', +'Likelihood', +'NormalizedBoundingBox', +'ShotChangeDetectionConfig', +'VideoAnnotationProgress', +'VideoAnnotationResults', +'VideoContext', +'VideoIntelligenceServiceClient', +'VideoSegment', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json new file mode 100644 index 00000000..478a3473 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.videointelligence_v1beta2", + "protoPackage": "google.cloud.videointelligence.v1beta2", + "schema": "1.0", + "services": { + "VideoIntelligenceService": { + "clients": { + "grpc": { + "libraryClient": "VideoIntelligenceServiceClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VideoIntelligenceServiceAsyncClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py new file mode 100644 index 00000000..4094cd26 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VideoIntelligenceServiceClient +from .async_client import VideoIntelligenceServiceAsyncClient + +__all__ = ( + 'VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py new file mode 100644 index 00000000..f50b7b49 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1beta2.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport +from .client import VideoIntelligenceServiceClient + + +class VideoIntelligenceServiceAsyncClient: + """Service that implements Google Cloud Video Intelligence API.""" + + _client: VideoIntelligenceServiceClient + + DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) + parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) + common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) + parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VideoIntelligenceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def annotate_video(self, + request: video_intelligence.AnnotateVideoRequest = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (:class:`google.cloud.videointelligence_v1beta2.types.AnnotateVideoRequest`): + The request object. Video annotation request. + input_uri (:class:`str`): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and + thus identify multiple videos. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + should be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (:class:`Sequence[google.cloud.videointelligence_v1beta2.types.Feature]`): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1beta2.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = video_intelligence.AnnotateVideoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features: + request.features.extend(features) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py new file mode 100644 index 00000000..f5828e59 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1beta2.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VideoIntelligenceServiceGrpcTransport +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +class VideoIntelligenceServiceClientMeta(type): + """Metaclass for the VideoIntelligenceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] + _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VideoIntelligenceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): + """Service that implements Google Cloud Video Intelligence API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "videointelligence.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VideoIntelligenceServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VideoIntelligenceServiceTransport): + # transport is a VideoIntelligenceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def annotate_video(self, + request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (Union[google.cloud.videointelligence_v1beta2.types.AnnotateVideoRequest, dict]): + The request object. Video annotation request. + input_uri (str): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and + thus identify multiple videos. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + should be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (Sequence[google.cloud.videointelligence_v1beta2.types.Feature]): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1beta2.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a video_intelligence.AnnotateVideoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, video_intelligence.AnnotateVideoRequest): + request = video_intelligence.AnnotateVideoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features is not None: + request.features = features + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.annotate_video] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceClient", +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py new file mode 100644 index 00000000..ef66f264 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VideoIntelligenceServiceTransport +from .grpc import VideoIntelligenceServiceGrpcTransport +from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] +_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport + +__all__ = ( + 'VideoIntelligenceServiceTransport', + 'VideoIntelligenceServiceGrpcTransport', + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py new file mode 100644 index 00000000..501c4281 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1beta2.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-videointelligence', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class VideoIntelligenceServiceTransport(abc.ABC): + """Abstract transport class for VideoIntelligenceService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'videointelligence.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.annotate_video: gapic_v1.method.wrap_method( + self.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VideoIntelligenceServiceTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py new file mode 100644 index 00000000..67292694 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.videointelligence_v1beta2.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO + + +class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): + """gRPC backend transport for VideoIntelligenceService. + + Service that implements Google Cloud Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + operations_pb2.Operation]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1beta2.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VideoIntelligenceServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..9015f0bf --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.videointelligence_v1beta2.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import VideoIntelligenceServiceGrpcTransport + + +class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): + """gRPC AsyncIO backend transport for VideoIntelligenceService. + + Service that implements Google Cloud Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1beta2.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py new file mode 100644 index 00000000..7058cf37 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py @@ -0,0 +1,68 @@ +# -*- 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 .video_intelligence import ( + AnnotateVideoProgress, + AnnotateVideoRequest, + AnnotateVideoResponse, + Entity, + ExplicitContentAnnotation, + ExplicitContentDetectionConfig, + ExplicitContentFrame, + FaceAnnotation, + FaceDetectionConfig, + FaceFrame, + FaceSegment, + LabelAnnotation, + LabelDetectionConfig, + LabelFrame, + LabelSegment, + NormalizedBoundingBox, + ShotChangeDetectionConfig, + VideoAnnotationProgress, + VideoAnnotationResults, + VideoContext, + VideoSegment, + Feature, + LabelDetectionMode, + Likelihood, +) + +__all__ = ( + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'FaceAnnotation', + 'FaceDetectionConfig', + 'FaceFrame', + 'FaceSegment', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'NormalizedBoundingBox', + 'ShotChangeDetectionConfig', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py new file mode 100644 index 00000000..fbb60081 --- /dev/null +++ b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py @@ -0,0 +1,718 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.videointelligence.v1beta2', + manifest={ + 'Feature', + 'LabelDetectionMode', + 'Likelihood', + 'AnnotateVideoRequest', + 'VideoContext', + 'LabelDetectionConfig', + 'ShotChangeDetectionConfig', + 'ExplicitContentDetectionConfig', + 'FaceDetectionConfig', + 'VideoSegment', + 'LabelSegment', + 'LabelFrame', + 'Entity', + 'LabelAnnotation', + 'ExplicitContentFrame', + 'ExplicitContentAnnotation', + 'NormalizedBoundingBox', + 'FaceSegment', + 'FaceFrame', + 'FaceAnnotation', + 'VideoAnnotationResults', + 'AnnotateVideoResponse', + 'VideoAnnotationProgress', + 'AnnotateVideoProgress', + }, +) + + +class Feature(proto.Enum): + r"""Video annotation feature.""" + FEATURE_UNSPECIFIED = 0 + LABEL_DETECTION = 1 + SHOT_CHANGE_DETECTION = 2 + EXPLICIT_CONTENT_DETECTION = 3 + FACE_DETECTION = 4 + + +class LabelDetectionMode(proto.Enum): + r"""Label detection mode.""" + LABEL_DETECTION_MODE_UNSPECIFIED = 0 + SHOT_MODE = 1 + FRAME_MODE = 2 + SHOT_AND_FRAME_MODE = 3 + + +class Likelihood(proto.Enum): + r"""Bucketized representation of likelihood.""" + LIKELIHOOD_UNSPECIFIED = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class AnnotateVideoRequest(proto.Message): + r"""Video annotation request. + + Attributes: + input_uri (str): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and thus + identify multiple videos. Supported wildcards: '*' to match + 0 or more characters; '?' to match 1 character. If unset, + the input video should be embedded in the request as + ``input_content``. If set, ``input_content`` should be + unset. + input_content (bytes): + The video data bytes. If unset, the input video(s) should be + specified via ``input_uri``. If set, ``input_uri`` should be + unset. + features (Sequence[google.cloud.videointelligence_v1beta2.types.Feature]): + Required. Requested video annotation + features. + video_context (google.cloud.videointelligence_v1beta2.types.VideoContext): + Additional video context and/or feature- + pecific parameters. + output_uri (str): + Optional. Location where the output (in JSON format) should + be stored. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + location_id (str): + Optional. Cloud region where annotation should take place. + Supported cloud regions: ``us-east1``, ``us-west1``, + ``europe-west1``, ``asia-east1``. If no region is specified, + a region will be determined based on video file location. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + input_content = proto.Field( + proto.BYTES, + number=6, + ) + features = proto.RepeatedField( + proto.ENUM, + number=2, + enum='Feature', + ) + video_context = proto.Field( + proto.MESSAGE, + number=3, + message='VideoContext', + ) + output_uri = proto.Field( + proto.STRING, + number=4, + ) + location_id = proto.Field( + proto.STRING, + number=5, + ) + + +class VideoContext(proto.Message): + r"""Video context and/or feature-specific parameters. + + Attributes: + segments (Sequence[google.cloud.videointelligence_v1beta2.types.VideoSegment]): + Video segments to annotate. The segments may + overlap and are not required to be contiguous or + span the whole video. If unspecified, each video + is treated as a single segment. + label_detection_config (google.cloud.videointelligence_v1beta2.types.LabelDetectionConfig): + Config for LABEL_DETECTION. + shot_change_detection_config (google.cloud.videointelligence_v1beta2.types.ShotChangeDetectionConfig): + Config for SHOT_CHANGE_DETECTION. + explicit_content_detection_config (google.cloud.videointelligence_v1beta2.types.ExplicitContentDetectionConfig): + Config for EXPLICIT_CONTENT_DETECTION. + face_detection_config (google.cloud.videointelligence_v1beta2.types.FaceDetectionConfig): + Config for FACE_DETECTION. + """ + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + label_detection_config = proto.Field( + proto.MESSAGE, + number=2, + message='LabelDetectionConfig', + ) + shot_change_detection_config = proto.Field( + proto.MESSAGE, + number=3, + message='ShotChangeDetectionConfig', + ) + explicit_content_detection_config = proto.Field( + proto.MESSAGE, + number=4, + message='ExplicitContentDetectionConfig', + ) + face_detection_config = proto.Field( + proto.MESSAGE, + number=5, + message='FaceDetectionConfig', + ) + + +class LabelDetectionConfig(proto.Message): + r"""Config for LABEL_DETECTION. + + Attributes: + label_detection_mode (google.cloud.videointelligence_v1beta2.types.LabelDetectionMode): + What labels should be detected with LABEL_DETECTION, in + addition to video-level labels or segment-level labels. If + unspecified, defaults to ``SHOT_MODE``. + stationary_camera (bool): + Whether the video has been shot from a stationary (i.e. + non-moving) camera. When set to true, might improve + detection accuracy for moving objects. Should be used with + ``SHOT_AND_FRAME_MODE`` enabled. + model (str): + Model to use for label detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + label_detection_mode = proto.Field( + proto.ENUM, + number=1, + enum='LabelDetectionMode', + ) + stationary_camera = proto.Field( + proto.BOOL, + number=2, + ) + model = proto.Field( + proto.STRING, + number=3, + ) + + +class ShotChangeDetectionConfig(proto.Message): + r"""Config for SHOT_CHANGE_DETECTION. + + Attributes: + model (str): + Model to use for shot change detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class ExplicitContentDetectionConfig(proto.Message): + r"""Config for EXPLICIT_CONTENT_DETECTION. + + Attributes: + model (str): + Model to use for explicit content detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class FaceDetectionConfig(proto.Message): + r"""Config for FACE_DETECTION. + + Attributes: + model (str): + Model to use for face detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + include_bounding_boxes (bool): + Whether bounding boxes be included in the + face annotation output. + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + include_bounding_boxes = proto.Field( + proto.BOOL, + number=2, + ) + + +class VideoSegment(proto.Message): + r"""Video segment. + + Attributes: + start_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the start of the segment + (inclusive). + end_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the end of the segment + (inclusive). + """ + + start_time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class LabelSegment(proto.Message): + r"""Video segment level annotation results for label detection. + + Attributes: + segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): + Video segment where a label was detected. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class LabelFrame(proto.Message): + r"""Video frame level annotation results for label detection. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class Entity(proto.Message): + r"""Detected entity from video analysis. + + Attributes: + entity_id (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + description (str): + Textual description, e.g. ``Fixed-gear bicycle``. + language_code (str): + Language code for ``description`` in BCP-47 format. + """ + + entity_id = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class LabelAnnotation(proto.Message): + r"""Label annotation. + + Attributes: + entity (google.cloud.videointelligence_v1beta2.types.Entity): + Detected entity. + category_entities (Sequence[google.cloud.videointelligence_v1beta2.types.Entity]): + Common categories for the detected entity. E.g. when the + label is ``Terrier`` the category is likely ``dog``. And in + some cases there might be more than one categories e.g. + ``Terrier`` could also be a ``pet``. + segments (Sequence[google.cloud.videointelligence_v1beta2.types.LabelSegment]): + All video segments where a label was + detected. + frames (Sequence[google.cloud.videointelligence_v1beta2.types.LabelFrame]): + All video frames where a label was detected. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + category_entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Entity', + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelSegment', + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelFrame', + ) + + +class ExplicitContentFrame(proto.Message): + r"""Video frame level annotation results for explicit content. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + pornography_likelihood (google.cloud.videointelligence_v1beta2.types.Likelihood): + Likelihood of the pornography content.. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + pornography_likelihood = proto.Field( + proto.ENUM, + number=2, + enum='Likelihood', + ) + + +class ExplicitContentAnnotation(proto.Message): + r"""Explicit content annotation (based on per-frame visual + signals only). If no explicit content has been detected in a + frame, no annotations are present for that frame. + + Attributes: + frames (Sequence[google.cloud.videointelligence_v1beta2.types.ExplicitContentFrame]): + All video frames where explicit content was + detected. + """ + + frames = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExplicitContentFrame', + ) + + +class NormalizedBoundingBox(proto.Message): + r"""Normalized bounding box. The normalized vertex coordinates are + relative to the original image. Range: [0, 1]. + + Attributes: + left (float): + Left X coordinate. + top (float): + Top Y coordinate. + right (float): + Right X coordinate. + bottom (float): + Bottom Y coordinate. + """ + + left = proto.Field( + proto.FLOAT, + number=1, + ) + top = proto.Field( + proto.FLOAT, + number=2, + ) + right = proto.Field( + proto.FLOAT, + number=3, + ) + bottom = proto.Field( + proto.FLOAT, + number=4, + ) + + +class FaceSegment(proto.Message): + r"""Video segment level annotation results for face detection. + + Attributes: + segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): + Video segment where a face was detected. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + + +class FaceFrame(proto.Message): + r"""Video frame level annotation results for face detection. + + Attributes: + normalized_bounding_boxes (Sequence[google.cloud.videointelligence_v1beta2.types.NormalizedBoundingBox]): + Normalized Bounding boxes in a frame. + There can be more than one boxes if the same + face is detected in multiple locations within + the current frame. + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + """ + + normalized_bounding_boxes = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedBoundingBox', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class FaceAnnotation(proto.Message): + r"""Face annotation. + + Attributes: + thumbnail (bytes): + Thumbnail of a representative face view (in + JPEG format). + segments (Sequence[google.cloud.videointelligence_v1beta2.types.FaceSegment]): + All video segments where a face was detected. + frames (Sequence[google.cloud.videointelligence_v1beta2.types.FaceFrame]): + All video frames where a face was detected. + """ + + thumbnail = proto.Field( + proto.BYTES, + number=1, + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='FaceSegment', + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='FaceFrame', + ) + + +class VideoAnnotationResults(proto.Message): + r"""Annotation results for a single video. + + Attributes: + input_uri (str): + Video file location in `Google Cloud + Storage `__. + segment_label_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.LabelAnnotation]): + Label annotations on video level or user + specified segment level. There is exactly one + element for each unique label. + shot_label_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.LabelAnnotation]): + Label annotations on shot level. + There is exactly one element for each unique + label. + frame_label_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.LabelAnnotation]): + Label annotations on frame level. + There is exactly one element for each unique + label. + face_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.FaceAnnotation]): + Face annotations. There is exactly one + element for each unique face. + shot_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.VideoSegment]): + Shot annotations. Each shot is represented as + a video segment. + explicit_annotation (google.cloud.videointelligence_v1beta2.types.ExplicitContentAnnotation): + Explicit content annotation. + error (google.rpc.status_pb2.Status): + If set, indicates an error. Note that for a single + ``AnnotateVideoRequest`` some videos may succeed and some + may fail. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + segment_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='LabelAnnotation', + ) + shot_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelAnnotation', + ) + frame_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelAnnotation', + ) + face_annotations = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='FaceAnnotation', + ) + shot_annotations = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='VideoSegment', + ) + explicit_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='ExplicitContentAnnotation', + ) + error = proto.Field( + proto.MESSAGE, + number=9, + message=status_pb2.Status, + ) + + +class AnnotateVideoResponse(proto.Message): + r"""Video annotation response. Included in the ``response`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_results (Sequence[google.cloud.videointelligence_v1beta2.types.VideoAnnotationResults]): + Annotation results for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationResults', + ) + + +class VideoAnnotationProgress(proto.Message): + r"""Annotation progress for a single video. + + Attributes: + input_uri (str): + Video file location in `Google Cloud + Storage `__. + progress_percent (int): + Approximate percentage processed thus far. + Guaranteed to be 100 when fully processed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent update. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + progress_percent = proto.Field( + proto.INT32, + number=2, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class AnnotateVideoProgress(proto.Message): + r"""Video annotation progress. Included in the ``metadata`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_progress (Sequence[google.cloud.videointelligence_v1beta2.types.VideoAnnotationProgress]): + Progress metadata for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_progress = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationProgress', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/mypy.ini b/owl-bot-staging/v1beta2/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1beta2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1beta2/noxfile.py b/owl-bot-staging/v1beta2/noxfile.py new file mode 100644 index 00000000..45c1942e --- /dev/null +++ b/owl-bot-staging/v1beta2/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/videointelligence_v1beta2/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py b/owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py new file mode 100644 index 00000000..7c1a29e9 --- /dev/null +++ b/owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class videointelligenceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=videointelligenceCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the videointelligence client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta2/setup.py b/owl-bot-staging/v1beta2/setup.py new file mode 100644 index 00000000..87b7ba3d --- /dev/null +++ b/owl-bot-staging/v1beta2/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-videointelligence', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta2/tests/__init__.py b/owl-bot-staging/v1beta2/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/__init__.py b/owl-bot-staging/v1beta2/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py b/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py new file mode 100644 index 00000000..3f88d4f3 --- /dev/null +++ b/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py @@ -0,0 +1,1177 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.videointelligence_v1beta2.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient +from google.cloud.videointelligence_v1beta2.services.video_intelligence_service import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1beta2.services.video_intelligence_service import transports +from google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.videointelligence_v1beta2.types import video_intelligence +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_client_get_transport_class(): + transport = VideoIntelligenceServiceClient.get_transport_class() + available_transports = [ + transports.VideoIntelligenceServiceGrpcTransport, + ] + assert transport in available_transports + + transport = VideoIntelligenceServiceClient.get_transport_class("grpc") + assert transport == transports.VideoIntelligenceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_video_intelligence_service_client_client_options_from_dict(): + with mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VideoIntelligenceServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_annotate_video_from_dict(): + test_annotate_video(request_type=dict) + + +def test_annotate_video_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + client.annotate_video() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + +@pytest.mark.asyncio +async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_annotate_video_async_from_dict(): + await test_annotate_video_async(request_type=dict) + + +def test_annotate_video_flattened(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +def test_annotate_video_flattened_error(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_error_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VideoIntelligenceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VideoIntelligenceServiceGrpcTransport, + ) + +def test_video_intelligence_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_video_intelligence_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'annotate_video', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_video_intelligence_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "videointelligence.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="videointelligence.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_video_intelligence_service_host_no_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_host_with_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:8000' + +def test_video_intelligence_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_video_intelligence_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_video_intelligence_service_grpc_lro_client(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_video_intelligence_service_grpc_lro_async_client(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = VideoIntelligenceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = VideoIntelligenceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VideoIntelligenceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = VideoIntelligenceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = VideoIntelligenceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = VideoIntelligenceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VideoIntelligenceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = VideoIntelligenceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = VideoIntelligenceServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc new file mode 100644 index 00000000..45c608f8 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/videointelligence/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p1beta1/MANIFEST.in b/owl-bot-staging/v1p1beta1/MANIFEST.in new file mode 100644 index 00000000..93a795ab --- /dev/null +++ b/owl-bot-staging/v1p1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/videointelligence *.py +recursive-include google/cloud/videointelligence_v1p1beta1 *.py diff --git a/owl-bot-staging/v1p1beta1/README.rst b/owl-bot-staging/v1p1beta1/README.rst new file mode 100644 index 00000000..bedc3680 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Videointelligence API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Videointelligence API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1p1beta1/docs/conf.py b/owl-bot-staging/v1p1beta1/docs/conf.py new file mode 100644 index 00000000..7a82f64b --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-videointelligence documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-videointelligence" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-videointelligence-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-videointelligence.tex", + u"google-cloud-videointelligence Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-videointelligence", + u"Google Cloud Videointelligence Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-videointelligence", + u"google-cloud-videointelligence Documentation", + author, + "google-cloud-videointelligence", + "GAPIC library for Google Cloud Videointelligence API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1p1beta1/docs/index.rst b/owl-bot-staging/v1p1beta1/docs/index.rst new file mode 100644 index 00000000..30457695 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + videointelligence_v1p1beta1/services + videointelligence_v1p1beta1/types diff --git a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst new file mode 100644 index 00000000..a26a19fe --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Videointelligence v1p1beta1 API +========================================================= +.. toctree:: + :maxdepth: 2 + + video_intelligence_service diff --git a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst new file mode 100644 index 00000000..2aa52bbf --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Videointelligence v1p1beta1 API +====================================================== + +.. automodule:: google.cloud.videointelligence_v1p1beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst new file mode 100644 index 00000000..423a835c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst @@ -0,0 +1,6 @@ +VideoIntelligenceService +------------------------------------------ + +.. automodule:: google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py new file mode 100644 index 00000000..1e443c3a --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py @@ -0,0 +1,71 @@ +# -*- 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.videointelligence_v1p1beta1.services.video_intelligence_service.client import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient + +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import AnnotateVideoProgress +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import AnnotateVideoRequest +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import AnnotateVideoResponse +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import Entity +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ExplicitContentAnnotation +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ExplicitContentDetectionConfig +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ExplicitContentFrame +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelAnnotation +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelDetectionConfig +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelFrame +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelSegment +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ShotChangeDetectionConfig +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechContext +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechRecognitionAlternative +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechTranscription +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechTranscriptionConfig +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoAnnotationProgress +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoAnnotationResults +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoContext +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoSegment +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import WordInfo +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import Feature +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelDetectionMode +from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import Likelihood + +__all__ = ('VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'ShotChangeDetectionConfig', + 'SpeechContext', + 'SpeechRecognitionAlternative', + 'SpeechTranscription', + 'SpeechTranscriptionConfig', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'WordInfo', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py new file mode 100644 index 00000000..77c1f395 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.video_intelligence_service import VideoIntelligenceServiceClient +from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient + +from .types.video_intelligence import AnnotateVideoProgress +from .types.video_intelligence import AnnotateVideoRequest +from .types.video_intelligence import AnnotateVideoResponse +from .types.video_intelligence import Entity +from .types.video_intelligence import ExplicitContentAnnotation +from .types.video_intelligence import ExplicitContentDetectionConfig +from .types.video_intelligence import ExplicitContentFrame +from .types.video_intelligence import LabelAnnotation +from .types.video_intelligence import LabelDetectionConfig +from .types.video_intelligence import LabelFrame +from .types.video_intelligence import LabelSegment +from .types.video_intelligence import ShotChangeDetectionConfig +from .types.video_intelligence import SpeechContext +from .types.video_intelligence import SpeechRecognitionAlternative +from .types.video_intelligence import SpeechTranscription +from .types.video_intelligence import SpeechTranscriptionConfig +from .types.video_intelligence import VideoAnnotationProgress +from .types.video_intelligence import VideoAnnotationResults +from .types.video_intelligence import VideoContext +from .types.video_intelligence import VideoSegment +from .types.video_intelligence import WordInfo +from .types.video_intelligence import Feature +from .types.video_intelligence import LabelDetectionMode +from .types.video_intelligence import Likelihood + +__all__ = ( + 'VideoIntelligenceServiceAsyncClient', +'AnnotateVideoProgress', +'AnnotateVideoRequest', +'AnnotateVideoResponse', +'Entity', +'ExplicitContentAnnotation', +'ExplicitContentDetectionConfig', +'ExplicitContentFrame', +'Feature', +'LabelAnnotation', +'LabelDetectionConfig', +'LabelDetectionMode', +'LabelFrame', +'LabelSegment', +'Likelihood', +'ShotChangeDetectionConfig', +'SpeechContext', +'SpeechRecognitionAlternative', +'SpeechTranscription', +'SpeechTranscriptionConfig', +'VideoAnnotationProgress', +'VideoAnnotationResults', +'VideoContext', +'VideoIntelligenceServiceClient', +'VideoSegment', +'WordInfo', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json new file mode 100644 index 00000000..6af0aca3 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.videointelligence_v1p1beta1", + "protoPackage": "google.cloud.videointelligence.v1p1beta1", + "schema": "1.0", + "services": { + "VideoIntelligenceService": { + "clients": { + "grpc": { + "libraryClient": "VideoIntelligenceServiceClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VideoIntelligenceServiceAsyncClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py new file mode 100644 index 00000000..4094cd26 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VideoIntelligenceServiceClient +from .async_client import VideoIntelligenceServiceAsyncClient + +__all__ = ( + 'VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py new file mode 100644 index 00000000..8ad1215a --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1p1beta1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport +from .client import VideoIntelligenceServiceClient + + +class VideoIntelligenceServiceAsyncClient: + """Service that implements Google Cloud Video Intelligence API.""" + + _client: VideoIntelligenceServiceClient + + DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) + parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) + common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) + parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VideoIntelligenceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def annotate_video(self, + request: video_intelligence.AnnotateVideoRequest = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (:class:`google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoRequest`): + The request object. Video annotation request. + input_uri (:class:`str`): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and + thus identify multiple videos. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + should be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (:class:`Sequence[google.cloud.videointelligence_v1p1beta1.types.Feature]`): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = video_intelligence.AnnotateVideoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features: + request.features.extend(features) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py new file mode 100644 index 00000000..8012f685 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1p1beta1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VideoIntelligenceServiceGrpcTransport +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +class VideoIntelligenceServiceClientMeta(type): + """Metaclass for the VideoIntelligenceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] + _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VideoIntelligenceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): + """Service that implements Google Cloud Video Intelligence API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "videointelligence.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VideoIntelligenceServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VideoIntelligenceServiceTransport): + # transport is a VideoIntelligenceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def annotate_video(self, + request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (Union[google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoRequest, dict]): + The request object. Video annotation request. + input_uri (str): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and + thus identify multiple videos. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + should be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (Sequence[google.cloud.videointelligence_v1p1beta1.types.Feature]): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a video_intelligence.AnnotateVideoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, video_intelligence.AnnotateVideoRequest): + request = video_intelligence.AnnotateVideoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features is not None: + request.features = features + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.annotate_video] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceClient", +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py new file mode 100644 index 00000000..ef66f264 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VideoIntelligenceServiceTransport +from .grpc import VideoIntelligenceServiceGrpcTransport +from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] +_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport + +__all__ = ( + 'VideoIntelligenceServiceTransport', + 'VideoIntelligenceServiceGrpcTransport', + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py new file mode 100644 index 00000000..69f19f4e --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1p1beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-videointelligence', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class VideoIntelligenceServiceTransport(abc.ABC): + """Abstract transport class for VideoIntelligenceService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'videointelligence.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.annotate_video: gapic_v1.method.wrap_method( + self.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VideoIntelligenceServiceTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py new file mode 100644 index 00000000..621e0427 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.videointelligence_v1p1beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO + + +class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): + """gRPC backend transport for VideoIntelligenceService. + + Service that implements Google Cloud Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + operations_pb2.Operation]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VideoIntelligenceServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..d9842db5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.videointelligence_v1p1beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import VideoIntelligenceServiceGrpcTransport + + +class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): + """gRPC AsyncIO backend transport for VideoIntelligenceService. + + Service that implements Google Cloud Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py new file mode 100644 index 00000000..4eba1b6f --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py @@ -0,0 +1,68 @@ +# -*- 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 .video_intelligence import ( + AnnotateVideoProgress, + AnnotateVideoRequest, + AnnotateVideoResponse, + Entity, + ExplicitContentAnnotation, + ExplicitContentDetectionConfig, + ExplicitContentFrame, + LabelAnnotation, + LabelDetectionConfig, + LabelFrame, + LabelSegment, + ShotChangeDetectionConfig, + SpeechContext, + SpeechRecognitionAlternative, + SpeechTranscription, + SpeechTranscriptionConfig, + VideoAnnotationProgress, + VideoAnnotationResults, + VideoContext, + VideoSegment, + WordInfo, + Feature, + LabelDetectionMode, + Likelihood, +) + +__all__ = ( + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'ShotChangeDetectionConfig', + 'SpeechContext', + 'SpeechRecognitionAlternative', + 'SpeechTranscription', + 'SpeechTranscriptionConfig', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'WordInfo', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py new file mode 100644 index 00000000..7dc6af1b --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py @@ -0,0 +1,779 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.videointelligence.v1p1beta1', + manifest={ + 'Feature', + 'LabelDetectionMode', + 'Likelihood', + 'AnnotateVideoRequest', + 'VideoContext', + 'LabelDetectionConfig', + 'ShotChangeDetectionConfig', + 'ExplicitContentDetectionConfig', + 'VideoSegment', + 'LabelSegment', + 'LabelFrame', + 'Entity', + 'LabelAnnotation', + 'ExplicitContentFrame', + 'ExplicitContentAnnotation', + 'VideoAnnotationResults', + 'AnnotateVideoResponse', + 'VideoAnnotationProgress', + 'AnnotateVideoProgress', + 'SpeechTranscriptionConfig', + 'SpeechContext', + 'SpeechTranscription', + 'SpeechRecognitionAlternative', + 'WordInfo', + }, +) + + +class Feature(proto.Enum): + r"""Video annotation feature.""" + FEATURE_UNSPECIFIED = 0 + LABEL_DETECTION = 1 + SHOT_CHANGE_DETECTION = 2 + EXPLICIT_CONTENT_DETECTION = 3 + SPEECH_TRANSCRIPTION = 6 + + +class LabelDetectionMode(proto.Enum): + r"""Label detection mode.""" + LABEL_DETECTION_MODE_UNSPECIFIED = 0 + SHOT_MODE = 1 + FRAME_MODE = 2 + SHOT_AND_FRAME_MODE = 3 + + +class Likelihood(proto.Enum): + r"""Bucketized representation of likelihood.""" + LIKELIHOOD_UNSPECIFIED = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class AnnotateVideoRequest(proto.Message): + r"""Video annotation request. + + Attributes: + input_uri (str): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and thus + identify multiple videos. Supported wildcards: '*' to match + 0 or more characters; '?' to match 1 character. If unset, + the input video should be embedded in the request as + ``input_content``. If set, ``input_content`` should be + unset. + input_content (bytes): + The video data bytes. If unset, the input video(s) should be + specified via ``input_uri``. If set, ``input_uri`` should be + unset. + features (Sequence[google.cloud.videointelligence_v1p1beta1.types.Feature]): + Required. Requested video annotation + features. + video_context (google.cloud.videointelligence_v1p1beta1.types.VideoContext): + Additional video context and/or feature- + pecific parameters. + output_uri (str): + Optional. Location where the output (in JSON format) should + be stored. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + location_id (str): + Optional. Cloud region where annotation should take place. + Supported cloud regions: ``us-east1``, ``us-west1``, + ``europe-west1``, ``asia-east1``. If no region is specified, + a region will be determined based on video file location. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + input_content = proto.Field( + proto.BYTES, + number=6, + ) + features = proto.RepeatedField( + proto.ENUM, + number=2, + enum='Feature', + ) + video_context = proto.Field( + proto.MESSAGE, + number=3, + message='VideoContext', + ) + output_uri = proto.Field( + proto.STRING, + number=4, + ) + location_id = proto.Field( + proto.STRING, + number=5, + ) + + +class VideoContext(proto.Message): + r"""Video context and/or feature-specific parameters. + + Attributes: + segments (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoSegment]): + Video segments to annotate. The segments may + overlap and are not required to be contiguous or + span the whole video. If unspecified, each video + is treated as a single segment. + label_detection_config (google.cloud.videointelligence_v1p1beta1.types.LabelDetectionConfig): + Config for LABEL_DETECTION. + shot_change_detection_config (google.cloud.videointelligence_v1p1beta1.types.ShotChangeDetectionConfig): + Config for SHOT_CHANGE_DETECTION. + explicit_content_detection_config (google.cloud.videointelligence_v1p1beta1.types.ExplicitContentDetectionConfig): + Config for EXPLICIT_CONTENT_DETECTION. + speech_transcription_config (google.cloud.videointelligence_v1p1beta1.types.SpeechTranscriptionConfig): + Config for SPEECH_TRANSCRIPTION. + """ + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + label_detection_config = proto.Field( + proto.MESSAGE, + number=2, + message='LabelDetectionConfig', + ) + shot_change_detection_config = proto.Field( + proto.MESSAGE, + number=3, + message='ShotChangeDetectionConfig', + ) + explicit_content_detection_config = proto.Field( + proto.MESSAGE, + number=4, + message='ExplicitContentDetectionConfig', + ) + speech_transcription_config = proto.Field( + proto.MESSAGE, + number=6, + message='SpeechTranscriptionConfig', + ) + + +class LabelDetectionConfig(proto.Message): + r"""Config for LABEL_DETECTION. + + Attributes: + label_detection_mode (google.cloud.videointelligence_v1p1beta1.types.LabelDetectionMode): + What labels should be detected with LABEL_DETECTION, in + addition to video-level labels or segment-level labels. If + unspecified, defaults to ``SHOT_MODE``. + stationary_camera (bool): + Whether the video has been shot from a stationary (i.e. + non-moving) camera. When set to true, might improve + detection accuracy for moving objects. Should be used with + ``SHOT_AND_FRAME_MODE`` enabled. + model (str): + Model to use for label detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + label_detection_mode = proto.Field( + proto.ENUM, + number=1, + enum='LabelDetectionMode', + ) + stationary_camera = proto.Field( + proto.BOOL, + number=2, + ) + model = proto.Field( + proto.STRING, + number=3, + ) + + +class ShotChangeDetectionConfig(proto.Message): + r"""Config for SHOT_CHANGE_DETECTION. + + Attributes: + model (str): + Model to use for shot change detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class ExplicitContentDetectionConfig(proto.Message): + r"""Config for EXPLICIT_CONTENT_DETECTION. + + Attributes: + model (str): + Model to use for explicit content detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class VideoSegment(proto.Message): + r"""Video segment. + + Attributes: + start_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the start of the segment + (inclusive). + end_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the end of the segment + (inclusive). + """ + + start_time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class LabelSegment(proto.Message): + r"""Video segment level annotation results for label detection. + + Attributes: + segment (google.cloud.videointelligence_v1p1beta1.types.VideoSegment): + Video segment where a label was detected. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class LabelFrame(proto.Message): + r"""Video frame level annotation results for label detection. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class Entity(proto.Message): + r"""Detected entity from video analysis. + + Attributes: + entity_id (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + description (str): + Textual description, e.g. ``Fixed-gear bicycle``. + language_code (str): + Language code for ``description`` in BCP-47 format. + """ + + entity_id = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class LabelAnnotation(proto.Message): + r"""Label annotation. + + Attributes: + entity (google.cloud.videointelligence_v1p1beta1.types.Entity): + Detected entity. + category_entities (Sequence[google.cloud.videointelligence_v1p1beta1.types.Entity]): + Common categories for the detected entity. E.g. when the + label is ``Terrier`` the category is likely ``dog``. And in + some cases there might be more than one categories e.g. + ``Terrier`` could also be a ``pet``. + segments (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelSegment]): + All video segments where a label was + detected. + frames (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelFrame]): + All video frames where a label was detected. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + category_entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Entity', + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelSegment', + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelFrame', + ) + + +class ExplicitContentFrame(proto.Message): + r"""Video frame level annotation results for explicit content. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + pornography_likelihood (google.cloud.videointelligence_v1p1beta1.types.Likelihood): + Likelihood of the pornography content.. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + pornography_likelihood = proto.Field( + proto.ENUM, + number=2, + enum='Likelihood', + ) + + +class ExplicitContentAnnotation(proto.Message): + r"""Explicit content annotation (based on per-frame visual + signals only). If no explicit content has been detected in a + frame, no annotations are present for that frame. + + Attributes: + frames (Sequence[google.cloud.videointelligence_v1p1beta1.types.ExplicitContentFrame]): + All video frames where explicit content was + detected. + """ + + frames = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExplicitContentFrame', + ) + + +class VideoAnnotationResults(proto.Message): + r"""Annotation results for a single video. + + Attributes: + input_uri (str): + Output only. Video file location in `Google Cloud + Storage `__. + segment_label_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelAnnotation]): + Label annotations on video level or user + specified segment level. There is exactly one + element for each unique label. + shot_label_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelAnnotation]): + Label annotations on shot level. + There is exactly one element for each unique + label. + frame_label_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelAnnotation]): + Label annotations on frame level. + There is exactly one element for each unique + label. + shot_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoSegment]): + Shot annotations. Each shot is represented as + a video segment. + explicit_annotation (google.cloud.videointelligence_v1p1beta1.types.ExplicitContentAnnotation): + Explicit content annotation. + speech_transcriptions (Sequence[google.cloud.videointelligence_v1p1beta1.types.SpeechTranscription]): + Speech transcription. + error (google.rpc.status_pb2.Status): + Output only. If set, indicates an error. Note that for a + single ``AnnotateVideoRequest`` some videos may succeed and + some may fail. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + segment_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='LabelAnnotation', + ) + shot_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelAnnotation', + ) + frame_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelAnnotation', + ) + shot_annotations = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='VideoSegment', + ) + explicit_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='ExplicitContentAnnotation', + ) + speech_transcriptions = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='SpeechTranscription', + ) + error = proto.Field( + proto.MESSAGE, + number=9, + message=status_pb2.Status, + ) + + +class AnnotateVideoResponse(proto.Message): + r"""Video annotation response. Included in the ``response`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_results (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoAnnotationResults]): + Annotation results for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationResults', + ) + + +class VideoAnnotationProgress(proto.Message): + r"""Annotation progress for a single video. + + Attributes: + input_uri (str): + Output only. Video file location in `Google Cloud + Storage `__. + progress_percent (int): + Output only. Approximate percentage processed + thus far. Guaranteed to be 100 when fully + processed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the request was + received. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time of the most recent update. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + progress_percent = proto.Field( + proto.INT32, + number=2, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class AnnotateVideoProgress(proto.Message): + r"""Video annotation progress. Included in the ``metadata`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_progress (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoAnnotationProgress]): + Progress metadata for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_progress = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationProgress', + ) + + +class SpeechTranscriptionConfig(proto.Message): + r"""Config for SPEECH_TRANSCRIPTION. + + Attributes: + language_code (str): + Required. *Required* The language of the supplied audio as a + `BCP-47 `__ + language tag. Example: "en-US". See `Language + Support `__ + for a list of the currently supported language codes. + max_alternatives (int): + Optional. Maximum number of recognition hypotheses to be + returned. Specifically, the maximum number of + ``SpeechRecognitionAlternative`` messages within each + ``SpeechTranscription``. The server may return fewer than + ``max_alternatives``. Valid values are ``0``-``30``. A value + of ``0`` or ``1`` will return a maximum of one. If omitted, + will return a maximum of one. + filter_profanity (bool): + Optional. If set to ``true``, the server will attempt to + filter out profanities, replacing all but the initial + character in each filtered word with asterisks, e.g. "f***". + If set to ``false`` or omitted, profanities won't be + filtered out. + speech_contexts (Sequence[google.cloud.videointelligence_v1p1beta1.types.SpeechContext]): + Optional. A means to provide context to + assist the speech recognition. + enable_automatic_punctuation (bool): + Optional. If 'true', adds punctuation to + recognition result hypotheses. This feature is + only available in select languages. Setting this + for requests in other languages has no effect at + all. The default 'false' value does not add + punctuation to result hypotheses. NOTE: "This is + currently offered as an experimental service, + complimentary to all users. In the future this + may be exclusively available as a premium + feature.". + audio_tracks (Sequence[int]): + Optional. For file formats, such as MXF or + MKV, supporting multiple audio tracks, specify + up to two tracks. Default: track 0. + """ + + language_code = proto.Field( + proto.STRING, + number=1, + ) + max_alternatives = proto.Field( + proto.INT32, + number=2, + ) + filter_profanity = proto.Field( + proto.BOOL, + number=3, + ) + speech_contexts = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SpeechContext', + ) + enable_automatic_punctuation = proto.Field( + proto.BOOL, + number=5, + ) + audio_tracks = proto.RepeatedField( + proto.INT32, + number=6, + ) + + +class SpeechContext(proto.Message): + r"""Provides "hints" to the speech recognizer to favor specific + words and phrases in the results. + + Attributes: + phrases (Sequence[str]): + Optional. A list of strings containing words and phrases + "hints" so that the speech recognition is more likely to + recognize them. This can be used to improve the accuracy for + specific words and phrases, for example, if specific + commands are typically spoken by the user. This can also be + used to add additional words to the vocabulary of the + recognizer. See `usage + limits `__. + """ + + phrases = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class SpeechTranscription(proto.Message): + r"""A speech recognition result corresponding to a portion of the + audio. + + Attributes: + alternatives (Sequence[google.cloud.videointelligence_v1p1beta1.types.SpeechRecognitionAlternative]): + May contain one or more recognition hypotheses (up to the + maximum specified in ``max_alternatives``). These + alternatives are ordered in terms of accuracy, with the top + (first) alternative being the most probable, as ranked by + the recognizer. + """ + + alternatives = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SpeechRecognitionAlternative', + ) + + +class SpeechRecognitionAlternative(proto.Message): + r"""Alternative hypotheses (a.k.a. n-best list). + + Attributes: + transcript (str): + Output only. Transcript text representing the + words that the user spoke. + confidence (float): + Output only. The confidence estimate between 0.0 and 1.0. A + higher number indicates an estimated greater likelihood that + the recognized words are correct. This field is set only for + the top alternative. This field is not guaranteed to be + accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + words (Sequence[google.cloud.videointelligence_v1p1beta1.types.WordInfo]): + Output only. A list of word-specific + information for each recognized word. + """ + + transcript = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + words = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='WordInfo', + ) + + +class WordInfo(proto.Message): + r"""Word-specific information for recognized words. Word information is + only included in the response when certain request parameters are + set, such as ``enable_word_time_offsets``. + + Attributes: + start_time (google.protobuf.duration_pb2.Duration): + Output only. Time offset relative to the beginning of the + audio, and corresponding to the start of the spoken word. + This field is only set if ``enable_word_time_offsets=true`` + and only in the top hypothesis. This is an experimental + feature and the accuracy of the time offset can vary. + end_time (google.protobuf.duration_pb2.Duration): + Output only. Time offset relative to the beginning of the + audio, and corresponding to the end of the spoken word. This + field is only set if ``enable_word_time_offsets=true`` and + only in the top hypothesis. This is an experimental feature + and the accuracy of the time offset can vary. + word (str): + Output only. The word corresponding to this + set of information. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + word = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/mypy.ini b/owl-bot-staging/v1p1beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1p1beta1/noxfile.py b/owl-bot-staging/v1p1beta1/noxfile.py new file mode 100644 index 00000000..69fa0116 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/videointelligence_v1p1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py b/owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py new file mode 100644 index 00000000..7c1a29e9 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class videointelligenceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=videointelligenceCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the videointelligence client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1p1beta1/setup.py b/owl-bot-staging/v1p1beta1/setup.py new file mode 100644 index 00000000..87b7ba3d --- /dev/null +++ b/owl-bot-staging/v1p1beta1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-videointelligence', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py new file mode 100644 index 00000000..485bc189 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py @@ -0,0 +1,1177 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient +from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service import transports +from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.videointelligence_v1p1beta1.types import video_intelligence +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_client_get_transport_class(): + transport = VideoIntelligenceServiceClient.get_transport_class() + available_transports = [ + transports.VideoIntelligenceServiceGrpcTransport, + ] + assert transport in available_transports + + transport = VideoIntelligenceServiceClient.get_transport_class("grpc") + assert transport == transports.VideoIntelligenceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_video_intelligence_service_client_client_options_from_dict(): + with mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VideoIntelligenceServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_annotate_video_from_dict(): + test_annotate_video(request_type=dict) + + +def test_annotate_video_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + client.annotate_video() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + +@pytest.mark.asyncio +async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_annotate_video_async_from_dict(): + await test_annotate_video_async(request_type=dict) + + +def test_annotate_video_flattened(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +def test_annotate_video_flattened_error(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_error_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VideoIntelligenceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VideoIntelligenceServiceGrpcTransport, + ) + +def test_video_intelligence_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_video_intelligence_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'annotate_video', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_video_intelligence_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "videointelligence.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="videointelligence.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_video_intelligence_service_host_no_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_host_with_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:8000' + +def test_video_intelligence_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_video_intelligence_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_video_intelligence_service_grpc_lro_client(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_video_intelligence_service_grpc_lro_async_client(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = VideoIntelligenceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = VideoIntelligenceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VideoIntelligenceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = VideoIntelligenceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = VideoIntelligenceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = VideoIntelligenceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VideoIntelligenceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = VideoIntelligenceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = VideoIntelligenceServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1p2beta1/.coveragerc b/owl-bot-staging/v1p2beta1/.coveragerc new file mode 100644 index 00000000..45c608f8 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/videointelligence/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p2beta1/MANIFEST.in b/owl-bot-staging/v1p2beta1/MANIFEST.in new file mode 100644 index 00000000..ad395ff2 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/videointelligence *.py +recursive-include google/cloud/videointelligence_v1p2beta1 *.py diff --git a/owl-bot-staging/v1p2beta1/README.rst b/owl-bot-staging/v1p2beta1/README.rst new file mode 100644 index 00000000..bedc3680 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Videointelligence API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Videointelligence API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1p2beta1/docs/conf.py b/owl-bot-staging/v1p2beta1/docs/conf.py new file mode 100644 index 00000000..7a82f64b --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-videointelligence documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-videointelligence" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-videointelligence-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-videointelligence.tex", + u"google-cloud-videointelligence Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-videointelligence", + u"Google Cloud Videointelligence Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-videointelligence", + u"google-cloud-videointelligence Documentation", + author, + "google-cloud-videointelligence", + "GAPIC library for Google Cloud Videointelligence API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1p2beta1/docs/index.rst b/owl-bot-staging/v1p2beta1/docs/index.rst new file mode 100644 index 00000000..f87fd687 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + videointelligence_v1p2beta1/services + videointelligence_v1p2beta1/types diff --git a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst new file mode 100644 index 00000000..e3029604 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Videointelligence v1p2beta1 API +========================================================= +.. toctree:: + :maxdepth: 2 + + video_intelligence_service diff --git a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst new file mode 100644 index 00000000..1825803c --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Videointelligence v1p2beta1 API +====================================================== + +.. automodule:: google.cloud.videointelligence_v1p2beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst new file mode 100644 index 00000000..804a5442 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst @@ -0,0 +1,6 @@ +VideoIntelligenceService +------------------------------------------ + +.. automodule:: google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py new file mode 100644 index 00000000..fa93b081 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py @@ -0,0 +1,79 @@ +# -*- 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.videointelligence_v1p2beta1.services.video_intelligence_service.client import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient + +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import AnnotateVideoProgress +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import AnnotateVideoRequest +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import AnnotateVideoResponse +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import Entity +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ExplicitContentAnnotation +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ExplicitContentDetectionConfig +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ExplicitContentFrame +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelAnnotation +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelDetectionConfig +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelFrame +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelSegment +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import NormalizedBoundingBox +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import NormalizedBoundingPoly +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import NormalizedVertex +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ObjectTrackingAnnotation +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ObjectTrackingFrame +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ShotChangeDetectionConfig +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextAnnotation +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextDetectionConfig +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextFrame +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextSegment +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoAnnotationProgress +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoAnnotationResults +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoContext +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoSegment +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import Feature +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelDetectionMode +from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import Likelihood + +__all__ = ('VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'NormalizedBoundingBox', + 'NormalizedBoundingPoly', + 'NormalizedVertex', + 'ObjectTrackingAnnotation', + 'ObjectTrackingFrame', + 'ShotChangeDetectionConfig', + 'TextAnnotation', + 'TextDetectionConfig', + 'TextFrame', + 'TextSegment', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py new file mode 100644 index 00000000..9ad8d5e5 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.video_intelligence_service import VideoIntelligenceServiceClient +from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient + +from .types.video_intelligence import AnnotateVideoProgress +from .types.video_intelligence import AnnotateVideoRequest +from .types.video_intelligence import AnnotateVideoResponse +from .types.video_intelligence import Entity +from .types.video_intelligence import ExplicitContentAnnotation +from .types.video_intelligence import ExplicitContentDetectionConfig +from .types.video_intelligence import ExplicitContentFrame +from .types.video_intelligence import LabelAnnotation +from .types.video_intelligence import LabelDetectionConfig +from .types.video_intelligence import LabelFrame +from .types.video_intelligence import LabelSegment +from .types.video_intelligence import NormalizedBoundingBox +from .types.video_intelligence import NormalizedBoundingPoly +from .types.video_intelligence import NormalizedVertex +from .types.video_intelligence import ObjectTrackingAnnotation +from .types.video_intelligence import ObjectTrackingFrame +from .types.video_intelligence import ShotChangeDetectionConfig +from .types.video_intelligence import TextAnnotation +from .types.video_intelligence import TextDetectionConfig +from .types.video_intelligence import TextFrame +from .types.video_intelligence import TextSegment +from .types.video_intelligence import VideoAnnotationProgress +from .types.video_intelligence import VideoAnnotationResults +from .types.video_intelligence import VideoContext +from .types.video_intelligence import VideoSegment +from .types.video_intelligence import Feature +from .types.video_intelligence import LabelDetectionMode +from .types.video_intelligence import Likelihood + +__all__ = ( + 'VideoIntelligenceServiceAsyncClient', +'AnnotateVideoProgress', +'AnnotateVideoRequest', +'AnnotateVideoResponse', +'Entity', +'ExplicitContentAnnotation', +'ExplicitContentDetectionConfig', +'ExplicitContentFrame', +'Feature', +'LabelAnnotation', +'LabelDetectionConfig', +'LabelDetectionMode', +'LabelFrame', +'LabelSegment', +'Likelihood', +'NormalizedBoundingBox', +'NormalizedBoundingPoly', +'NormalizedVertex', +'ObjectTrackingAnnotation', +'ObjectTrackingFrame', +'ShotChangeDetectionConfig', +'TextAnnotation', +'TextDetectionConfig', +'TextFrame', +'TextSegment', +'VideoAnnotationProgress', +'VideoAnnotationResults', +'VideoContext', +'VideoIntelligenceServiceClient', +'VideoSegment', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json new file mode 100644 index 00000000..3f52f8b4 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.videointelligence_v1p2beta1", + "protoPackage": "google.cloud.videointelligence.v1p2beta1", + "schema": "1.0", + "services": { + "VideoIntelligenceService": { + "clients": { + "grpc": { + "libraryClient": "VideoIntelligenceServiceClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VideoIntelligenceServiceAsyncClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py new file mode 100644 index 00000000..4094cd26 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VideoIntelligenceServiceClient +from .async_client import VideoIntelligenceServiceAsyncClient + +__all__ = ( + 'VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py new file mode 100644 index 00000000..f746897b --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1p2beta1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport +from .client import VideoIntelligenceServiceClient + + +class VideoIntelligenceServiceAsyncClient: + """Service that implements Google Cloud Video Intelligence API.""" + + _client: VideoIntelligenceServiceClient + + DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) + parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) + common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) + parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VideoIntelligenceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def annotate_video(self, + request: video_intelligence.AnnotateVideoRequest = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (:class:`google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoRequest`): + The request object. Video annotation request. + input_uri (:class:`str`): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and + thus identify multiple videos. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + should be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (:class:`Sequence[google.cloud.videointelligence_v1p2beta1.types.Feature]`): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = video_intelligence.AnnotateVideoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features: + request.features.extend(features) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py new file mode 100644 index 00000000..c03f1a30 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1p2beta1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VideoIntelligenceServiceGrpcTransport +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +class VideoIntelligenceServiceClientMeta(type): + """Metaclass for the VideoIntelligenceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] + _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VideoIntelligenceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): + """Service that implements Google Cloud Video Intelligence API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "videointelligence.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VideoIntelligenceServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VideoIntelligenceServiceTransport): + # transport is a VideoIntelligenceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def annotate_video(self, + request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (Union[google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoRequest, dict]): + The request object. Video annotation request. + input_uri (str): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and + thus identify multiple videos. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + should be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (Sequence[google.cloud.videointelligence_v1p2beta1.types.Feature]): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a video_intelligence.AnnotateVideoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, video_intelligence.AnnotateVideoRequest): + request = video_intelligence.AnnotateVideoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features is not None: + request.features = features + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.annotate_video] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceClient", +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py new file mode 100644 index 00000000..ef66f264 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VideoIntelligenceServiceTransport +from .grpc import VideoIntelligenceServiceGrpcTransport +from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] +_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport + +__all__ = ( + 'VideoIntelligenceServiceTransport', + 'VideoIntelligenceServiceGrpcTransport', + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py new file mode 100644 index 00000000..48f5ef11 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1p2beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-videointelligence', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class VideoIntelligenceServiceTransport(abc.ABC): + """Abstract transport class for VideoIntelligenceService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'videointelligence.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.annotate_video: gapic_v1.method.wrap_method( + self.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VideoIntelligenceServiceTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py new file mode 100644 index 00000000..99811cd3 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.videointelligence_v1p2beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO + + +class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): + """gRPC backend transport for VideoIntelligenceService. + + Service that implements Google Cloud Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + operations_pb2.Operation]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VideoIntelligenceServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..da9634df --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.videointelligence_v1p2beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import VideoIntelligenceServiceGrpcTransport + + +class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): + """gRPC AsyncIO backend transport for VideoIntelligenceService. + + Service that implements Google Cloud Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py new file mode 100644 index 00000000..a3d9ea0d --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py @@ -0,0 +1,76 @@ +# -*- 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 .video_intelligence import ( + AnnotateVideoProgress, + AnnotateVideoRequest, + AnnotateVideoResponse, + Entity, + ExplicitContentAnnotation, + ExplicitContentDetectionConfig, + ExplicitContentFrame, + LabelAnnotation, + LabelDetectionConfig, + LabelFrame, + LabelSegment, + NormalizedBoundingBox, + NormalizedBoundingPoly, + NormalizedVertex, + ObjectTrackingAnnotation, + ObjectTrackingFrame, + ShotChangeDetectionConfig, + TextAnnotation, + TextDetectionConfig, + TextFrame, + TextSegment, + VideoAnnotationProgress, + VideoAnnotationResults, + VideoContext, + VideoSegment, + Feature, + LabelDetectionMode, + Likelihood, +) + +__all__ = ( + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'NormalizedBoundingBox', + 'NormalizedBoundingPoly', + 'NormalizedVertex', + 'ObjectTrackingAnnotation', + 'ObjectTrackingFrame', + 'ShotChangeDetectionConfig', + 'TextAnnotation', + 'TextDetectionConfig', + 'TextFrame', + 'TextSegment', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py new file mode 100644 index 00000000..183599c2 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py @@ -0,0 +1,853 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.videointelligence.v1p2beta1', + manifest={ + 'Feature', + 'LabelDetectionMode', + 'Likelihood', + 'AnnotateVideoRequest', + 'VideoContext', + 'LabelDetectionConfig', + 'ShotChangeDetectionConfig', + 'ExplicitContentDetectionConfig', + 'TextDetectionConfig', + 'VideoSegment', + 'LabelSegment', + 'LabelFrame', + 'Entity', + 'LabelAnnotation', + 'ExplicitContentFrame', + 'ExplicitContentAnnotation', + 'NormalizedBoundingBox', + 'VideoAnnotationResults', + 'AnnotateVideoResponse', + 'VideoAnnotationProgress', + 'AnnotateVideoProgress', + 'NormalizedVertex', + 'NormalizedBoundingPoly', + 'TextSegment', + 'TextFrame', + 'TextAnnotation', + 'ObjectTrackingFrame', + 'ObjectTrackingAnnotation', + }, +) + + +class Feature(proto.Enum): + r"""Video annotation feature.""" + FEATURE_UNSPECIFIED = 0 + LABEL_DETECTION = 1 + SHOT_CHANGE_DETECTION = 2 + EXPLICIT_CONTENT_DETECTION = 3 + TEXT_DETECTION = 7 + OBJECT_TRACKING = 9 + + +class LabelDetectionMode(proto.Enum): + r"""Label detection mode.""" + LABEL_DETECTION_MODE_UNSPECIFIED = 0 + SHOT_MODE = 1 + FRAME_MODE = 2 + SHOT_AND_FRAME_MODE = 3 + + +class Likelihood(proto.Enum): + r"""Bucketized representation of likelihood.""" + LIKELIHOOD_UNSPECIFIED = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class AnnotateVideoRequest(proto.Message): + r"""Video annotation request. + + Attributes: + input_uri (str): + Input video location. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + A video URI may include wildcards in ``object-id``, and thus + identify multiple videos. Supported wildcards: '*' to match + 0 or more characters; '?' to match 1 character. If unset, + the input video should be embedded in the request as + ``input_content``. If set, ``input_content`` should be + unset. + input_content (bytes): + The video data bytes. If unset, the input video(s) should be + specified via ``input_uri``. If set, ``input_uri`` should be + unset. + features (Sequence[google.cloud.videointelligence_v1p2beta1.types.Feature]): + Required. Requested video annotation + features. + video_context (google.cloud.videointelligence_v1p2beta1.types.VideoContext): + Additional video context and/or feature- + pecific parameters. + output_uri (str): + Optional. Location where the output (in JSON format) should + be stored. Currently, only `Google Cloud + Storage `__ URIs are + supported, which must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + location_id (str): + Optional. Cloud region where annotation should take place. + Supported cloud regions: ``us-east1``, ``us-west1``, + ``europe-west1``, ``asia-east1``. If no region is specified, + a region will be determined based on video file location. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + input_content = proto.Field( + proto.BYTES, + number=6, + ) + features = proto.RepeatedField( + proto.ENUM, + number=2, + enum='Feature', + ) + video_context = proto.Field( + proto.MESSAGE, + number=3, + message='VideoContext', + ) + output_uri = proto.Field( + proto.STRING, + number=4, + ) + location_id = proto.Field( + proto.STRING, + number=5, + ) + + +class VideoContext(proto.Message): + r"""Video context and/or feature-specific parameters. + + Attributes: + segments (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoSegment]): + Video segments to annotate. The segments may + overlap and are not required to be contiguous or + span the whole video. If unspecified, each video + is treated as a single segment. + label_detection_config (google.cloud.videointelligence_v1p2beta1.types.LabelDetectionConfig): + Config for LABEL_DETECTION. + shot_change_detection_config (google.cloud.videointelligence_v1p2beta1.types.ShotChangeDetectionConfig): + Config for SHOT_CHANGE_DETECTION. + explicit_content_detection_config (google.cloud.videointelligence_v1p2beta1.types.ExplicitContentDetectionConfig): + Config for EXPLICIT_CONTENT_DETECTION. + text_detection_config (google.cloud.videointelligence_v1p2beta1.types.TextDetectionConfig): + Config for TEXT_DETECTION. + """ + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + label_detection_config = proto.Field( + proto.MESSAGE, + number=2, + message='LabelDetectionConfig', + ) + shot_change_detection_config = proto.Field( + proto.MESSAGE, + number=3, + message='ShotChangeDetectionConfig', + ) + explicit_content_detection_config = proto.Field( + proto.MESSAGE, + number=4, + message='ExplicitContentDetectionConfig', + ) + text_detection_config = proto.Field( + proto.MESSAGE, + number=8, + message='TextDetectionConfig', + ) + + +class LabelDetectionConfig(proto.Message): + r"""Config for LABEL_DETECTION. + + Attributes: + label_detection_mode (google.cloud.videointelligence_v1p2beta1.types.LabelDetectionMode): + What labels should be detected with LABEL_DETECTION, in + addition to video-level labels or segment-level labels. If + unspecified, defaults to ``SHOT_MODE``. + stationary_camera (bool): + Whether the video has been shot from a stationary (i.e. + non-moving) camera. When set to true, might improve + detection accuracy for moving objects. Should be used with + ``SHOT_AND_FRAME_MODE`` enabled. + model (str): + Model to use for label detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + label_detection_mode = proto.Field( + proto.ENUM, + number=1, + enum='LabelDetectionMode', + ) + stationary_camera = proto.Field( + proto.BOOL, + number=2, + ) + model = proto.Field( + proto.STRING, + number=3, + ) + + +class ShotChangeDetectionConfig(proto.Message): + r"""Config for SHOT_CHANGE_DETECTION. + + Attributes: + model (str): + Model to use for shot change detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class ExplicitContentDetectionConfig(proto.Message): + r"""Config for EXPLICIT_CONTENT_DETECTION. + + Attributes: + model (str): + Model to use for explicit content detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class TextDetectionConfig(proto.Message): + r"""Config for TEXT_DETECTION. + + Attributes: + language_hints (Sequence[str]): + Language hint can be specified if the + language to be detected is known a priori. It + can increase the accuracy of the detection. + Language hint must be language code in BCP-47 + format. + + Automatic language detection is performed if no + hint is provided. + """ + + language_hints = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class VideoSegment(proto.Message): + r"""Video segment. + + Attributes: + start_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the start of the segment + (inclusive). + end_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the end of the segment + (inclusive). + """ + + start_time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class LabelSegment(proto.Message): + r"""Video segment level annotation results for label detection. + + Attributes: + segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): + Video segment where a label was detected. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class LabelFrame(proto.Message): + r"""Video frame level annotation results for label detection. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class Entity(proto.Message): + r"""Detected entity from video analysis. + + Attributes: + entity_id (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + description (str): + Textual description, e.g. ``Fixed-gear bicycle``. + language_code (str): + Language code for ``description`` in BCP-47 format. + """ + + entity_id = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class LabelAnnotation(proto.Message): + r"""Label annotation. + + Attributes: + entity (google.cloud.videointelligence_v1p2beta1.types.Entity): + Detected entity. + category_entities (Sequence[google.cloud.videointelligence_v1p2beta1.types.Entity]): + Common categories for the detected entity. E.g. when the + label is ``Terrier`` the category is likely ``dog``. And in + some cases there might be more than one categories e.g. + ``Terrier`` could also be a ``pet``. + segments (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelSegment]): + All video segments where a label was + detected. + frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelFrame]): + All video frames where a label was detected. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + category_entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Entity', + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelSegment', + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelFrame', + ) + + +class ExplicitContentFrame(proto.Message): + r"""Video frame level annotation results for explicit content. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + pornography_likelihood (google.cloud.videointelligence_v1p2beta1.types.Likelihood): + Likelihood of the pornography content.. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + pornography_likelihood = proto.Field( + proto.ENUM, + number=2, + enum='Likelihood', + ) + + +class ExplicitContentAnnotation(proto.Message): + r"""Explicit content annotation (based on per-frame visual + signals only). If no explicit content has been detected in a + frame, no annotations are present for that frame. + + Attributes: + frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.ExplicitContentFrame]): + All video frames where explicit content was + detected. + """ + + frames = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExplicitContentFrame', + ) + + +class NormalizedBoundingBox(proto.Message): + r"""Normalized bounding box. The normalized vertex coordinates are + relative to the original image. Range: [0, 1]. + + Attributes: + left (float): + Left X coordinate. + top (float): + Top Y coordinate. + right (float): + Right X coordinate. + bottom (float): + Bottom Y coordinate. + """ + + left = proto.Field( + proto.FLOAT, + number=1, + ) + top = proto.Field( + proto.FLOAT, + number=2, + ) + right = proto.Field( + proto.FLOAT, + number=3, + ) + bottom = proto.Field( + proto.FLOAT, + number=4, + ) + + +class VideoAnnotationResults(proto.Message): + r"""Annotation results for a single video. + + Attributes: + input_uri (str): + Video file location in `Google Cloud + Storage `__. + segment_label_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelAnnotation]): + Label annotations on video level or user + specified segment level. There is exactly one + element for each unique label. + shot_label_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelAnnotation]): + Label annotations on shot level. + There is exactly one element for each unique + label. + frame_label_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelAnnotation]): + Label annotations on frame level. + There is exactly one element for each unique + label. + shot_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoSegment]): + Shot annotations. Each shot is represented as + a video segment. + explicit_annotation (google.cloud.videointelligence_v1p2beta1.types.ExplicitContentAnnotation): + Explicit content annotation. + text_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.TextAnnotation]): + OCR text detection and tracking. + Annotations for list of detected text snippets. + Each will have list of frame information + associated with it. + object_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.ObjectTrackingAnnotation]): + Annotations for list of objects detected and + tracked in video. + error (google.rpc.status_pb2.Status): + If set, indicates an error. Note that for a single + ``AnnotateVideoRequest`` some videos may succeed and some + may fail. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + segment_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='LabelAnnotation', + ) + shot_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelAnnotation', + ) + frame_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelAnnotation', + ) + shot_annotations = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='VideoSegment', + ) + explicit_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='ExplicitContentAnnotation', + ) + text_annotations = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='TextAnnotation', + ) + object_annotations = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='ObjectTrackingAnnotation', + ) + error = proto.Field( + proto.MESSAGE, + number=9, + message=status_pb2.Status, + ) + + +class AnnotateVideoResponse(proto.Message): + r"""Video annotation response. Included in the ``response`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_results (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoAnnotationResults]): + Annotation results for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationResults', + ) + + +class VideoAnnotationProgress(proto.Message): + r"""Annotation progress for a single video. + + Attributes: + input_uri (str): + Video file location in `Google Cloud + Storage `__. + progress_percent (int): + Approximate percentage processed thus far. + Guaranteed to be 100 when fully processed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent update. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + progress_percent = proto.Field( + proto.INT32, + number=2, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class AnnotateVideoProgress(proto.Message): + r"""Video annotation progress. Included in the ``metadata`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_progress (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoAnnotationProgress]): + Progress metadata for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_progress = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationProgress', + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field( + proto.FLOAT, + number=1, + ) + y = proto.Field( + proto.FLOAT, + number=2, + ) + + +class NormalizedBoundingPoly(proto.Message): + r"""Normalized bounding polygon for text (that might not be aligned with + axis). Contains list of the corner points in clockwise order + starting from top-left corner. For example, for a rectangular + bounding box: When the text is horizontal it might look like: 0----1 + \| \| 3----2 + + When it's clockwise rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 + + and the vertex order will still be (0, 1, 2, 3). Note that values + can be less than 0, or greater than 1 due to trignometric + calculations for location of the box. + + Attributes: + vertices (Sequence[google.cloud.videointelligence_v1p2beta1.types.NormalizedVertex]): + Normalized vertices of the bounding polygon. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class TextSegment(proto.Message): + r"""Video segment level annotation results for text detection. + + Attributes: + segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): + Video segment where a text snippet was + detected. + confidence (float): + Confidence for the track of detected text. It + is calculated as the highest over all frames + where OCR detected text appears. + frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.TextFrame]): + Information related to the frames where OCR + detected text appears. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='TextFrame', + ) + + +class TextFrame(proto.Message): + r"""Video frame level annotation results for text annotation + (OCR). Contains information regarding timestamp and bounding box + locations for the frames containing detected OCR text snippets. + + Attributes: + rotated_bounding_box (google.cloud.videointelligence_v1p2beta1.types.NormalizedBoundingPoly): + Bounding polygon of the detected text for + this frame. + time_offset (google.protobuf.duration_pb2.Duration): + Timestamp of this frame. + """ + + rotated_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingPoly', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class TextAnnotation(proto.Message): + r"""Annotations related to one detected OCR text snippet. This + will contain the corresponding text, confidence value, and frame + level information for each detection. + + Attributes: + text (str): + The detected text. + segments (Sequence[google.cloud.videointelligence_v1p2beta1.types.TextSegment]): + All video segments where OCR detected text + appears. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TextSegment', + ) + + +class ObjectTrackingFrame(proto.Message): + r"""Video frame level annotations for object detection and + tracking. This field stores per frame location, time offset, and + confidence. + + Attributes: + normalized_bounding_box (google.cloud.videointelligence_v1p2beta1.types.NormalizedBoundingBox): + The normalized bounding box location of this + object track for the frame. + time_offset (google.protobuf.duration_pb2.Duration): + The timestamp of the frame in microseconds. + """ + + normalized_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingBox', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ObjectTrackingAnnotation(proto.Message): + r"""Annotations corresponding to one tracked object. + + Attributes: + entity (google.cloud.videointelligence_v1p2beta1.types.Entity): + Entity to specify the object category that + this track is labeled as. + confidence (float): + Object category's labeling confidence of this + track. + frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.ObjectTrackingFrame]): + Information corresponding to all frames where + this object track appears. + segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): + Each object track corresponds to one video + segment where it appears. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ObjectTrackingFrame', + ) + segment = proto.Field( + proto.MESSAGE, + number=3, + message='VideoSegment', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p2beta1/mypy.ini b/owl-bot-staging/v1p2beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1p2beta1/noxfile.py b/owl-bot-staging/v1p2beta1/noxfile.py new file mode 100644 index 00000000..eb91250c --- /dev/null +++ b/owl-bot-staging/v1p2beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/videointelligence_v1p2beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py b/owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py new file mode 100644 index 00000000..7c1a29e9 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class videointelligenceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=videointelligenceCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the videointelligence client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1p2beta1/setup.py b/owl-bot-staging/v1p2beta1/setup.py new file mode 100644 index 00000000..87b7ba3d --- /dev/null +++ b/owl-bot-staging/v1p2beta1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-videointelligence', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1p2beta1/tests/__init__.py b/owl-bot-staging/v1p2beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py new file mode 100644 index 00000000..093b38f4 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py @@ -0,0 +1,1177 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient +from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service import transports +from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.videointelligence_v1p2beta1.types import video_intelligence +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_client_get_transport_class(): + transport = VideoIntelligenceServiceClient.get_transport_class() + available_transports = [ + transports.VideoIntelligenceServiceGrpcTransport, + ] + assert transport in available_transports + + transport = VideoIntelligenceServiceClient.get_transport_class("grpc") + assert transport == transports.VideoIntelligenceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_video_intelligence_service_client_client_options_from_dict(): + with mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VideoIntelligenceServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_annotate_video_from_dict(): + test_annotate_video(request_type=dict) + + +def test_annotate_video_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + client.annotate_video() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + +@pytest.mark.asyncio +async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_annotate_video_async_from_dict(): + await test_annotate_video_async(request_type=dict) + + +def test_annotate_video_flattened(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +def test_annotate_video_flattened_error(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_error_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VideoIntelligenceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VideoIntelligenceServiceGrpcTransport, + ) + +def test_video_intelligence_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_video_intelligence_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'annotate_video', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_video_intelligence_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "videointelligence.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="videointelligence.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_video_intelligence_service_host_no_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_host_with_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:8000' + +def test_video_intelligence_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_video_intelligence_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_video_intelligence_service_grpc_lro_client(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_video_intelligence_service_grpc_lro_async_client(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = VideoIntelligenceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = VideoIntelligenceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VideoIntelligenceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = VideoIntelligenceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = VideoIntelligenceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = VideoIntelligenceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VideoIntelligenceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = VideoIntelligenceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = VideoIntelligenceServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1p3beta1/.coveragerc b/owl-bot-staging/v1p3beta1/.coveragerc new file mode 100644 index 00000000..45c608f8 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/videointelligence/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p3beta1/MANIFEST.in b/owl-bot-staging/v1p3beta1/MANIFEST.in new file mode 100644 index 00000000..e35640e6 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/videointelligence *.py +recursive-include google/cloud/videointelligence_v1p3beta1 *.py diff --git a/owl-bot-staging/v1p3beta1/README.rst b/owl-bot-staging/v1p3beta1/README.rst new file mode 100644 index 00000000..bedc3680 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Videointelligence API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Videointelligence API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1p3beta1/docs/conf.py b/owl-bot-staging/v1p3beta1/docs/conf.py new file mode 100644 index 00000000..7a82f64b --- /dev/null +++ b/owl-bot-staging/v1p3beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-videointelligence documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-videointelligence" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-videointelligence-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-videointelligence.tex", + u"google-cloud-videointelligence Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-videointelligence", + u"Google Cloud Videointelligence Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-videointelligence", + u"google-cloud-videointelligence Documentation", + author, + "google-cloud-videointelligence", + "GAPIC library for Google Cloud Videointelligence API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1p3beta1/docs/index.rst b/owl-bot-staging/v1p3beta1/docs/index.rst new file mode 100644 index 00000000..259bf4fc --- /dev/null +++ b/owl-bot-staging/v1p3beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + videointelligence_v1p3beta1/services + videointelligence_v1p3beta1/types diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst new file mode 100644 index 00000000..853cb921 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Videointelligence v1p3beta1 API +========================================================= +.. toctree:: + :maxdepth: 2 + + streaming_video_intelligence_service + video_intelligence_service diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst new file mode 100644 index 00000000..4de59243 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst @@ -0,0 +1,6 @@ +StreamingVideoIntelligenceService +--------------------------------------------------- + +.. automodule:: google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst new file mode 100644 index 00000000..75c97809 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Videointelligence v1p3beta1 API +====================================================== + +.. automodule:: google.cloud.videointelligence_v1p3beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst new file mode 100644 index 00000000..fd06a199 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst @@ -0,0 +1,6 @@ +VideoIntelligenceService +------------------------------------------ + +.. automodule:: google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py new file mode 100644 index 00000000..5f45af06 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py @@ -0,0 +1,145 @@ +# -*- 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.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.client import StreamingVideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.async_client import StreamingVideoIntelligenceServiceAsyncClient +from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.client import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient + +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import AnnotateVideoProgress +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import AnnotateVideoRequest +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import AnnotateVideoResponse +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Celebrity +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import CelebrityRecognitionAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import CelebrityTrack +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import DetectedAttribute +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import DetectedLandmark +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Entity +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ExplicitContentAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ExplicitContentDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ExplicitContentFrame +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import FaceDetectionAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import FaceDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelFrame +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelSegment +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LogoRecognitionAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import NormalizedBoundingBox +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import NormalizedBoundingPoly +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import NormalizedVertex +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ObjectTrackingAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ObjectTrackingConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ObjectTrackingFrame +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import PersonDetectionAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import PersonDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ShotChangeDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechContext +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechRecognitionAlternative +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechTranscription +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechTranscriptionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAnnotateVideoRequest +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAnnotateVideoResponse +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAutomlActionRecognitionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAutomlClassificationConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAutomlObjectTrackingConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingExplicitContentDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingLabelDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingObjectTrackingConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingShotChangeDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingStorageConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingVideoAnnotationResults +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingVideoConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextAnnotation +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextDetectionConfig +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextFrame +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextSegment +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TimestampedObject +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Track +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoAnnotationProgress +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoAnnotationResults +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoContext +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoSegment +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import WordInfo +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Feature +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelDetectionMode +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Likelihood +from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingFeature + +__all__ = ('StreamingVideoIntelligenceServiceClient', + 'StreamingVideoIntelligenceServiceAsyncClient', + 'VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Celebrity', + 'CelebrityRecognitionAnnotation', + 'CelebrityTrack', + 'DetectedAttribute', + 'DetectedLandmark', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'FaceDetectionAnnotation', + 'FaceDetectionConfig', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'LogoRecognitionAnnotation', + 'NormalizedBoundingBox', + 'NormalizedBoundingPoly', + 'NormalizedVertex', + 'ObjectTrackingAnnotation', + 'ObjectTrackingConfig', + 'ObjectTrackingFrame', + 'PersonDetectionAnnotation', + 'PersonDetectionConfig', + 'ShotChangeDetectionConfig', + 'SpeechContext', + 'SpeechRecognitionAlternative', + 'SpeechTranscription', + 'SpeechTranscriptionConfig', + 'StreamingAnnotateVideoRequest', + 'StreamingAnnotateVideoResponse', + 'StreamingAutomlActionRecognitionConfig', + 'StreamingAutomlClassificationConfig', + 'StreamingAutomlObjectTrackingConfig', + 'StreamingExplicitContentDetectionConfig', + 'StreamingLabelDetectionConfig', + 'StreamingObjectTrackingConfig', + 'StreamingShotChangeDetectionConfig', + 'StreamingStorageConfig', + 'StreamingVideoAnnotationResults', + 'StreamingVideoConfig', + 'TextAnnotation', + 'TextDetectionConfig', + 'TextFrame', + 'TextSegment', + 'TimestampedObject', + 'Track', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'WordInfo', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', + 'StreamingFeature', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py new file mode 100644 index 00000000..d1c49b52 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceClient +from .services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceAsyncClient +from .services.video_intelligence_service import VideoIntelligenceServiceClient +from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient + +from .types.video_intelligence import AnnotateVideoProgress +from .types.video_intelligence import AnnotateVideoRequest +from .types.video_intelligence import AnnotateVideoResponse +from .types.video_intelligence import Celebrity +from .types.video_intelligence import CelebrityRecognitionAnnotation +from .types.video_intelligence import CelebrityTrack +from .types.video_intelligence import DetectedAttribute +from .types.video_intelligence import DetectedLandmark +from .types.video_intelligence import Entity +from .types.video_intelligence import ExplicitContentAnnotation +from .types.video_intelligence import ExplicitContentDetectionConfig +from .types.video_intelligence import ExplicitContentFrame +from .types.video_intelligence import FaceDetectionAnnotation +from .types.video_intelligence import FaceDetectionConfig +from .types.video_intelligence import LabelAnnotation +from .types.video_intelligence import LabelDetectionConfig +from .types.video_intelligence import LabelFrame +from .types.video_intelligence import LabelSegment +from .types.video_intelligence import LogoRecognitionAnnotation +from .types.video_intelligence import NormalizedBoundingBox +from .types.video_intelligence import NormalizedBoundingPoly +from .types.video_intelligence import NormalizedVertex +from .types.video_intelligence import ObjectTrackingAnnotation +from .types.video_intelligence import ObjectTrackingConfig +from .types.video_intelligence import ObjectTrackingFrame +from .types.video_intelligence import PersonDetectionAnnotation +from .types.video_intelligence import PersonDetectionConfig +from .types.video_intelligence import ShotChangeDetectionConfig +from .types.video_intelligence import SpeechContext +from .types.video_intelligence import SpeechRecognitionAlternative +from .types.video_intelligence import SpeechTranscription +from .types.video_intelligence import SpeechTranscriptionConfig +from .types.video_intelligence import StreamingAnnotateVideoRequest +from .types.video_intelligence import StreamingAnnotateVideoResponse +from .types.video_intelligence import StreamingAutomlActionRecognitionConfig +from .types.video_intelligence import StreamingAutomlClassificationConfig +from .types.video_intelligence import StreamingAutomlObjectTrackingConfig +from .types.video_intelligence import StreamingExplicitContentDetectionConfig +from .types.video_intelligence import StreamingLabelDetectionConfig +from .types.video_intelligence import StreamingObjectTrackingConfig +from .types.video_intelligence import StreamingShotChangeDetectionConfig +from .types.video_intelligence import StreamingStorageConfig +from .types.video_intelligence import StreamingVideoAnnotationResults +from .types.video_intelligence import StreamingVideoConfig +from .types.video_intelligence import TextAnnotation +from .types.video_intelligence import TextDetectionConfig +from .types.video_intelligence import TextFrame +from .types.video_intelligence import TextSegment +from .types.video_intelligence import TimestampedObject +from .types.video_intelligence import Track +from .types.video_intelligence import VideoAnnotationProgress +from .types.video_intelligence import VideoAnnotationResults +from .types.video_intelligence import VideoContext +from .types.video_intelligence import VideoSegment +from .types.video_intelligence import WordInfo +from .types.video_intelligence import Feature +from .types.video_intelligence import LabelDetectionMode +from .types.video_intelligence import Likelihood +from .types.video_intelligence import StreamingFeature + +__all__ = ( + 'StreamingVideoIntelligenceServiceAsyncClient', + 'VideoIntelligenceServiceAsyncClient', +'AnnotateVideoProgress', +'AnnotateVideoRequest', +'AnnotateVideoResponse', +'Celebrity', +'CelebrityRecognitionAnnotation', +'CelebrityTrack', +'DetectedAttribute', +'DetectedLandmark', +'Entity', +'ExplicitContentAnnotation', +'ExplicitContentDetectionConfig', +'ExplicitContentFrame', +'FaceDetectionAnnotation', +'FaceDetectionConfig', +'Feature', +'LabelAnnotation', +'LabelDetectionConfig', +'LabelDetectionMode', +'LabelFrame', +'LabelSegment', +'Likelihood', +'LogoRecognitionAnnotation', +'NormalizedBoundingBox', +'NormalizedBoundingPoly', +'NormalizedVertex', +'ObjectTrackingAnnotation', +'ObjectTrackingConfig', +'ObjectTrackingFrame', +'PersonDetectionAnnotation', +'PersonDetectionConfig', +'ShotChangeDetectionConfig', +'SpeechContext', +'SpeechRecognitionAlternative', +'SpeechTranscription', +'SpeechTranscriptionConfig', +'StreamingAnnotateVideoRequest', +'StreamingAnnotateVideoResponse', +'StreamingAutomlActionRecognitionConfig', +'StreamingAutomlClassificationConfig', +'StreamingAutomlObjectTrackingConfig', +'StreamingExplicitContentDetectionConfig', +'StreamingFeature', +'StreamingLabelDetectionConfig', +'StreamingObjectTrackingConfig', +'StreamingShotChangeDetectionConfig', +'StreamingStorageConfig', +'StreamingVideoAnnotationResults', +'StreamingVideoConfig', +'StreamingVideoIntelligenceServiceClient', +'TextAnnotation', +'TextDetectionConfig', +'TextFrame', +'TextSegment', +'TimestampedObject', +'Track', +'VideoAnnotationProgress', +'VideoAnnotationResults', +'VideoContext', +'VideoIntelligenceServiceClient', +'VideoSegment', +'WordInfo', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json new file mode 100644 index 00000000..040a74a1 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json @@ -0,0 +1,57 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.videointelligence_v1p3beta1", + "protoPackage": "google.cloud.videointelligence.v1p3beta1", + "schema": "1.0", + "services": { + "StreamingVideoIntelligenceService": { + "clients": { + "grpc": { + "libraryClient": "StreamingVideoIntelligenceServiceClient", + "rpcs": { + "StreamingAnnotateVideo": { + "methods": [ + "streaming_annotate_video" + ] + } + } + }, + "grpc-async": { + "libraryClient": "StreamingVideoIntelligenceServiceAsyncClient", + "rpcs": { + "StreamingAnnotateVideo": { + "methods": [ + "streaming_annotate_video" + ] + } + } + } + } + }, + "VideoIntelligenceService": { + "clients": { + "grpc": { + "libraryClient": "VideoIntelligenceServiceClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VideoIntelligenceServiceAsyncClient", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "annotate_video" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed new file mode 100644 index 00000000..e7fb166b --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py new file mode 100644 index 00000000..6dbf9507 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import StreamingVideoIntelligenceServiceClient +from .async_client import StreamingVideoIntelligenceServiceAsyncClient + +__all__ = ( + 'StreamingVideoIntelligenceServiceClient', + 'StreamingVideoIntelligenceServiceAsyncClient', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py new file mode 100644 index 00000000..13109fd6 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py @@ -0,0 +1,224 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from google.rpc import status_pb2 # type: ignore +from .transports.base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import StreamingVideoIntelligenceServiceGrpcAsyncIOTransport +from .client import StreamingVideoIntelligenceServiceClient + + +class StreamingVideoIntelligenceServiceAsyncClient: + """Service that implements streaming Video Intelligence API.""" + + _client: StreamingVideoIntelligenceServiceClient + + DEFAULT_ENDPOINT = StreamingVideoIntelligenceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = StreamingVideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_project_path) + parse_common_project_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_project_path) + common_location_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_location_path) + parse_common_location_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + StreamingVideoIntelligenceServiceAsyncClient: The constructed client. + """ + return StreamingVideoIntelligenceServiceClient.from_service_account_info.__func__(StreamingVideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + StreamingVideoIntelligenceServiceAsyncClient: The constructed client. + """ + return StreamingVideoIntelligenceServiceClient.from_service_account_file.__func__(StreamingVideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> StreamingVideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamingVideoIntelligenceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(StreamingVideoIntelligenceServiceClient).get_transport_class, type(StreamingVideoIntelligenceServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, StreamingVideoIntelligenceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streaming video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.StreamingVideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = StreamingVideoIntelligenceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + def streaming_annotate_video(self, + requests: AsyncIterator[video_intelligence.StreamingAnnotateVideoRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[video_intelligence.StreamingAnnotateVideoResponse]]: + r"""Performs video annotation with bidirectional + streaming: emitting results while sending video/audio + bytes. This method is only available via the gRPC API + (not REST). + + Args: + requests (AsyncIterator[`google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoRequest`]): + The request object AsyncIterator. The top-level message sent by the + client for the `StreamingAnnotateVideo` method. Multiple + `StreamingAnnotateVideoRequest` messages are sent. The + first message must only contain a `StreamingVideoConfig` + message. All subsequent messages must only contain + `input_content` data. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoResponse]: + StreamingAnnotateVideoResponse is the only message returned to the client + by StreamingAnnotateVideo. A series of zero or more + StreamingAnnotateVideoResponse messages are streamed + back to the client. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.streaming_annotate_video, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=10800.0, + ), + default_timeout=10800.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "StreamingVideoIntelligenceServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py new file mode 100644 index 00000000..c5cc429d --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py @@ -0,0 +1,401 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from google.rpc import status_pb2 # type: ignore +from .transports.base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import StreamingVideoIntelligenceServiceGrpcTransport +from .transports.grpc_asyncio import StreamingVideoIntelligenceServiceGrpcAsyncIOTransport + + +class StreamingVideoIntelligenceServiceClientMeta(type): + """Metaclass for the StreamingVideoIntelligenceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[StreamingVideoIntelligenceServiceTransport]] + _transport_registry["grpc"] = StreamingVideoIntelligenceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = StreamingVideoIntelligenceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[StreamingVideoIntelligenceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class StreamingVideoIntelligenceServiceClient(metaclass=StreamingVideoIntelligenceServiceClientMeta): + """Service that implements streaming Video Intelligence API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "videointelligence.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + StreamingVideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + StreamingVideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> StreamingVideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + StreamingVideoIntelligenceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, StreamingVideoIntelligenceServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the streaming video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, StreamingVideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, StreamingVideoIntelligenceServiceTransport): + # transport is a StreamingVideoIntelligenceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def streaming_annotate_video(self, + requests: Iterator[video_intelligence.StreamingAnnotateVideoRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[video_intelligence.StreamingAnnotateVideoResponse]: + r"""Performs video annotation with bidirectional + streaming: emitting results while sending video/audio + bytes. This method is only available via the gRPC API + (not REST). + + Args: + requests (Iterator[google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoRequest]): + The request object iterator. The top-level message sent by the + client for the `StreamingAnnotateVideo` method. Multiple + `StreamingAnnotateVideoRequest` messages are sent. The + first message must only contain a `StreamingVideoConfig` + message. All subsequent messages must only contain + `input_content` data. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoResponse]: + StreamingAnnotateVideoResponse is the only message returned to the client + by StreamingAnnotateVideo. A series of zero or more + StreamingAnnotateVideoResponse messages are streamed + back to the client. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_annotate_video] + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "StreamingVideoIntelligenceServiceClient", +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py new file mode 100644 index 00000000..90816d03 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import StreamingVideoIntelligenceServiceTransport +from .grpc import StreamingVideoIntelligenceServiceGrpcTransport +from .grpc_asyncio import StreamingVideoIntelligenceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[StreamingVideoIntelligenceServiceTransport]] +_transport_registry['grpc'] = StreamingVideoIntelligenceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = StreamingVideoIntelligenceServiceGrpcAsyncIOTransport + +__all__ = ( + 'StreamingVideoIntelligenceServiceTransport', + 'StreamingVideoIntelligenceServiceGrpcTransport', + 'StreamingVideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py new file mode 100644 index 00000000..81c59e8f --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-videointelligence', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class StreamingVideoIntelligenceServiceTransport(abc.ABC): + """Abstract transport class for StreamingVideoIntelligenceService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'videointelligence.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.streaming_annotate_video: gapic_v1.method.wrap_method( + self.streaming_annotate_video, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=10800.0, + ), + default_timeout=10800.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def streaming_annotate_video(self) -> Callable[ + [video_intelligence.StreamingAnnotateVideoRequest], + Union[ + video_intelligence.StreamingAnnotateVideoResponse, + Awaitable[video_intelligence.StreamingAnnotateVideoResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'StreamingVideoIntelligenceServiceTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py new file mode 100644 index 00000000..f189db30 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from .base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO + + +class StreamingVideoIntelligenceServiceGrpcTransport(StreamingVideoIntelligenceServiceTransport): + """gRPC backend transport for StreamingVideoIntelligenceService. + + Service that implements streaming Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def streaming_annotate_video(self) -> Callable[ + [video_intelligence.StreamingAnnotateVideoRequest], + video_intelligence.StreamingAnnotateVideoResponse]: + r"""Return a callable for the streaming annotate video method over gRPC. + + Performs video annotation with bidirectional + streaming: emitting results while sending video/audio + bytes. This method is only available via the gRPC API + (not REST). + + Returns: + Callable[[~.StreamingAnnotateVideoRequest], + ~.StreamingAnnotateVideoResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_annotate_video' not in self._stubs: + self._stubs['streaming_annotate_video'] = self.grpc_channel.stream_stream( + '/google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService/StreamingAnnotateVideo', + request_serializer=video_intelligence.StreamingAnnotateVideoRequest.serialize, + response_deserializer=video_intelligence.StreamingAnnotateVideoResponse.deserialize, + ) + return self._stubs['streaming_annotate_video'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'StreamingVideoIntelligenceServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..597332d5 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from .base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import StreamingVideoIntelligenceServiceGrpcTransport + + +class StreamingVideoIntelligenceServiceGrpcAsyncIOTransport(StreamingVideoIntelligenceServiceTransport): + """gRPC AsyncIO backend transport for StreamingVideoIntelligenceService. + + Service that implements streaming Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def streaming_annotate_video(self) -> Callable[ + [video_intelligence.StreamingAnnotateVideoRequest], + Awaitable[video_intelligence.StreamingAnnotateVideoResponse]]: + r"""Return a callable for the streaming annotate video method over gRPC. + + Performs video annotation with bidirectional + streaming: emitting results while sending video/audio + bytes. This method is only available via the gRPC API + (not REST). + + Returns: + Callable[[~.StreamingAnnotateVideoRequest], + Awaitable[~.StreamingAnnotateVideoResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_annotate_video' not in self._stubs: + self._stubs['streaming_annotate_video'] = self.grpc_channel.stream_stream( + '/google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService/StreamingAnnotateVideo', + request_serializer=video_intelligence.StreamingAnnotateVideoRequest.serialize, + response_deserializer=video_intelligence.StreamingAnnotateVideoResponse.deserialize, + ) + return self._stubs['streaming_annotate_video'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'StreamingVideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py new file mode 100644 index 00000000..4094cd26 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VideoIntelligenceServiceClient +from .async_client import VideoIntelligenceServiceAsyncClient + +__all__ = ( + 'VideoIntelligenceServiceClient', + 'VideoIntelligenceServiceAsyncClient', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py new file mode 100644 index 00000000..5c537982 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport +from .client import VideoIntelligenceServiceClient + + +class VideoIntelligenceServiceAsyncClient: + """Service that implements the Video Intelligence API.""" + + _client: VideoIntelligenceServiceClient + + DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) + parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) + common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) + parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceAsyncClient: The constructed client. + """ + return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VideoIntelligenceServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def annotate_video(self, + request: video_intelligence.AnnotateVideoRequest = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (:class:`google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoRequest`): + The request object. Video annotation request. + input_uri (:class:`str`): + Input video location. Currently, only `Cloud + Storage `__ URIs are + supported. URIs must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + To identify multiple videos, a video URI may include + wildcards in the ``object-id``. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + must be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (:class:`Sequence[google.cloud.videointelligence_v1p3beta1.types.Feature]`): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = video_intelligence.AnnotateVideoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features: + request.features.extend(features) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py new file mode 100644 index 00000000..fc127d7c --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VideoIntelligenceServiceGrpcTransport +from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +class VideoIntelligenceServiceClientMeta(type): + """Metaclass for the VideoIntelligenceService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] + _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VideoIntelligenceServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): + """Service that implements the Video Intelligence API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "videointelligence.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VideoIntelligenceServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VideoIntelligenceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VideoIntelligenceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VideoIntelligenceServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the video intelligence service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VideoIntelligenceServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VideoIntelligenceServiceTransport): + # transport is a VideoIntelligenceServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def annotate_video(self, + request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, + *, + input_uri: str = None, + features: Sequence[video_intelligence.Feature] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Args: + request (Union[google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoRequest, dict]): + The request object. Video annotation request. + input_uri (str): + Input video location. Currently, only `Cloud + Storage `__ URIs are + supported. URIs must be specified in the following + format: ``gs://bucket-id/object-id`` (other URI formats + return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + To identify multiple videos, a video URI may include + wildcards in the ``object-id``. Supported wildcards: '*' + to match 0 or more characters; '?' to match 1 character. + If unset, the input video should be embedded in the + request as ``input_content``. If set, ``input_content`` + must be unset. + + This corresponds to the ``input_uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + features (Sequence[google.cloud.videointelligence_v1p3beta1.types.Feature]): + Required. Requested video annotation + features. + + This corresponds to the ``features`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response + field of the Operation returned by the GetOperation + call of the google::longrunning::Operations service. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([input_uri, features]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a video_intelligence.AnnotateVideoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, video_intelligence.AnnotateVideoRequest): + request = video_intelligence.AnnotateVideoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if input_uri is not None: + request.input_uri = input_uri + if features is not None: + request.features = features + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.annotate_video] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + video_intelligence.AnnotateVideoResponse, + metadata_type=video_intelligence.AnnotateVideoProgress, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-videointelligence", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VideoIntelligenceServiceClient", +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py new file mode 100644 index 00000000..ef66f264 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VideoIntelligenceServiceTransport +from .grpc import VideoIntelligenceServiceGrpcTransport +from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] +_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport + +__all__ = ( + 'VideoIntelligenceServiceTransport', + 'VideoIntelligenceServiceGrpcTransport', + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py new file mode 100644 index 00000000..a7ad78fc --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-videointelligence', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class VideoIntelligenceServiceTransport(abc.ABC): + """Abstract transport class for VideoIntelligenceService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'videointelligence.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.annotate_video: gapic_v1.method.wrap_method( + self.annotate_video, + default_retry=retries.Retry( +initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VideoIntelligenceServiceTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py new file mode 100644 index 00000000..07368d0d --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO + + +class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): + """gRPC backend transport for VideoIntelligenceService. + + Service that implements the Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + operations_pb2.Operation]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VideoIntelligenceServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..e6fa875b --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from google.longrunning import operations_pb2 # type: ignore +from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import VideoIntelligenceServiceGrpcTransport + + +class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): + """gRPC AsyncIO backend transport for VideoIntelligenceService. + + Service that implements the Video Intelligence API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'videointelligence.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def annotate_video(self) -> Callable[ + [video_intelligence.AnnotateVideoRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the annotate video method over gRPC. + + Performs asynchronous video annotation. Progress and results can + be retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains + ``AnnotateVideoProgress`` (progress). ``Operation.response`` + contains ``AnnotateVideoResponse`` (results). + + Returns: + Callable[[~.AnnotateVideoRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'annotate_video' not in self._stubs: + self._stubs['annotate_video'] = self.grpc_channel.unary_unary( + '/google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService/AnnotateVideo', + request_serializer=video_intelligence.AnnotateVideoRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['annotate_video'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VideoIntelligenceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py new file mode 100644 index 00000000..ac168dda --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py @@ -0,0 +1,138 @@ +# -*- 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 .video_intelligence import ( + AnnotateVideoProgress, + AnnotateVideoRequest, + AnnotateVideoResponse, + Celebrity, + CelebrityRecognitionAnnotation, + CelebrityTrack, + DetectedAttribute, + DetectedLandmark, + Entity, + ExplicitContentAnnotation, + ExplicitContentDetectionConfig, + ExplicitContentFrame, + FaceDetectionAnnotation, + FaceDetectionConfig, + LabelAnnotation, + LabelDetectionConfig, + LabelFrame, + LabelSegment, + LogoRecognitionAnnotation, + NormalizedBoundingBox, + NormalizedBoundingPoly, + NormalizedVertex, + ObjectTrackingAnnotation, + ObjectTrackingConfig, + ObjectTrackingFrame, + PersonDetectionAnnotation, + PersonDetectionConfig, + ShotChangeDetectionConfig, + SpeechContext, + SpeechRecognitionAlternative, + SpeechTranscription, + SpeechTranscriptionConfig, + StreamingAnnotateVideoRequest, + StreamingAnnotateVideoResponse, + StreamingAutomlActionRecognitionConfig, + StreamingAutomlClassificationConfig, + StreamingAutomlObjectTrackingConfig, + StreamingExplicitContentDetectionConfig, + StreamingLabelDetectionConfig, + StreamingObjectTrackingConfig, + StreamingShotChangeDetectionConfig, + StreamingStorageConfig, + StreamingVideoAnnotationResults, + StreamingVideoConfig, + TextAnnotation, + TextDetectionConfig, + TextFrame, + TextSegment, + TimestampedObject, + Track, + VideoAnnotationProgress, + VideoAnnotationResults, + VideoContext, + VideoSegment, + WordInfo, + Feature, + LabelDetectionMode, + Likelihood, + StreamingFeature, +) + +__all__ = ( + 'AnnotateVideoProgress', + 'AnnotateVideoRequest', + 'AnnotateVideoResponse', + 'Celebrity', + 'CelebrityRecognitionAnnotation', + 'CelebrityTrack', + 'DetectedAttribute', + 'DetectedLandmark', + 'Entity', + 'ExplicitContentAnnotation', + 'ExplicitContentDetectionConfig', + 'ExplicitContentFrame', + 'FaceDetectionAnnotation', + 'FaceDetectionConfig', + 'LabelAnnotation', + 'LabelDetectionConfig', + 'LabelFrame', + 'LabelSegment', + 'LogoRecognitionAnnotation', + 'NormalizedBoundingBox', + 'NormalizedBoundingPoly', + 'NormalizedVertex', + 'ObjectTrackingAnnotation', + 'ObjectTrackingConfig', + 'ObjectTrackingFrame', + 'PersonDetectionAnnotation', + 'PersonDetectionConfig', + 'ShotChangeDetectionConfig', + 'SpeechContext', + 'SpeechRecognitionAlternative', + 'SpeechTranscription', + 'SpeechTranscriptionConfig', + 'StreamingAnnotateVideoRequest', + 'StreamingAnnotateVideoResponse', + 'StreamingAutomlActionRecognitionConfig', + 'StreamingAutomlClassificationConfig', + 'StreamingAutomlObjectTrackingConfig', + 'StreamingExplicitContentDetectionConfig', + 'StreamingLabelDetectionConfig', + 'StreamingObjectTrackingConfig', + 'StreamingShotChangeDetectionConfig', + 'StreamingStorageConfig', + 'StreamingVideoAnnotationResults', + 'StreamingVideoConfig', + 'TextAnnotation', + 'TextDetectionConfig', + 'TextFrame', + 'TextSegment', + 'TimestampedObject', + 'Track', + 'VideoAnnotationProgress', + 'VideoAnnotationResults', + 'VideoContext', + 'VideoSegment', + 'WordInfo', + 'Feature', + 'LabelDetectionMode', + 'Likelihood', + 'StreamingFeature', +) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py new file mode 100644 index 00000000..9786033a --- /dev/null +++ b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py @@ -0,0 +1,1998 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.videointelligence.v1p3beta1', + manifest={ + 'LabelDetectionMode', + 'Likelihood', + 'StreamingFeature', + 'Feature', + 'AnnotateVideoRequest', + 'VideoContext', + 'LabelDetectionConfig', + 'ShotChangeDetectionConfig', + 'ObjectTrackingConfig', + 'ExplicitContentDetectionConfig', + 'FaceDetectionConfig', + 'PersonDetectionConfig', + 'TextDetectionConfig', + 'VideoSegment', + 'LabelSegment', + 'LabelFrame', + 'Entity', + 'LabelAnnotation', + 'ExplicitContentFrame', + 'ExplicitContentAnnotation', + 'NormalizedBoundingBox', + 'TimestampedObject', + 'Track', + 'DetectedAttribute', + 'Celebrity', + 'CelebrityTrack', + 'CelebrityRecognitionAnnotation', + 'DetectedLandmark', + 'FaceDetectionAnnotation', + 'PersonDetectionAnnotation', + 'VideoAnnotationResults', + 'AnnotateVideoResponse', + 'VideoAnnotationProgress', + 'AnnotateVideoProgress', + 'SpeechTranscriptionConfig', + 'SpeechContext', + 'SpeechTranscription', + 'SpeechRecognitionAlternative', + 'WordInfo', + 'NormalizedVertex', + 'NormalizedBoundingPoly', + 'TextSegment', + 'TextFrame', + 'TextAnnotation', + 'ObjectTrackingFrame', + 'ObjectTrackingAnnotation', + 'LogoRecognitionAnnotation', + 'StreamingAnnotateVideoRequest', + 'StreamingVideoConfig', + 'StreamingAnnotateVideoResponse', + 'StreamingVideoAnnotationResults', + 'StreamingShotChangeDetectionConfig', + 'StreamingLabelDetectionConfig', + 'StreamingExplicitContentDetectionConfig', + 'StreamingObjectTrackingConfig', + 'StreamingAutomlActionRecognitionConfig', + 'StreamingAutomlClassificationConfig', + 'StreamingAutomlObjectTrackingConfig', + 'StreamingStorageConfig', + }, +) + + +class LabelDetectionMode(proto.Enum): + r"""Label detection mode.""" + LABEL_DETECTION_MODE_UNSPECIFIED = 0 + SHOT_MODE = 1 + FRAME_MODE = 2 + SHOT_AND_FRAME_MODE = 3 + + +class Likelihood(proto.Enum): + r"""Bucketized representation of likelihood.""" + LIKELIHOOD_UNSPECIFIED = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class StreamingFeature(proto.Enum): + r"""Streaming video annotation feature.""" + STREAMING_FEATURE_UNSPECIFIED = 0 + STREAMING_LABEL_DETECTION = 1 + STREAMING_SHOT_CHANGE_DETECTION = 2 + STREAMING_EXPLICIT_CONTENT_DETECTION = 3 + STREAMING_OBJECT_TRACKING = 4 + STREAMING_AUTOML_ACTION_RECOGNITION = 23 + STREAMING_AUTOML_CLASSIFICATION = 21 + STREAMING_AUTOML_OBJECT_TRACKING = 22 + + +class Feature(proto.Enum): + r"""Video annotation feature.""" + FEATURE_UNSPECIFIED = 0 + LABEL_DETECTION = 1 + SHOT_CHANGE_DETECTION = 2 + EXPLICIT_CONTENT_DETECTION = 3 + FACE_DETECTION = 4 + SPEECH_TRANSCRIPTION = 6 + TEXT_DETECTION = 7 + OBJECT_TRACKING = 9 + LOGO_RECOGNITION = 12 + CELEBRITY_RECOGNITION = 13 + PERSON_DETECTION = 14 + + +class AnnotateVideoRequest(proto.Message): + r"""Video annotation request. + + Attributes: + input_uri (str): + Input video location. Currently, only `Cloud + Storage `__ URIs are + supported. URIs must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + To identify multiple videos, a video URI may include + wildcards in the ``object-id``. Supported wildcards: '*' to + match 0 or more characters; '?' to match 1 character. If + unset, the input video should be embedded in the request as + ``input_content``. If set, ``input_content`` must be unset. + input_content (bytes): + The video data bytes. If unset, the input video(s) should be + specified via the ``input_uri``. If set, ``input_uri`` must + be unset. + features (Sequence[google.cloud.videointelligence_v1p3beta1.types.Feature]): + Required. Requested video annotation + features. + video_context (google.cloud.videointelligence_v1p3beta1.types.VideoContext): + Additional video context and/or feature- + pecific parameters. + output_uri (str): + Optional. Location where the output (in JSON format) should + be stored. Currently, only `Cloud + Storage `__ URIs are + supported. These must be specified in the following format: + ``gs://bucket-id/object-id`` (other URI formats return + [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). + For more information, see `Request + URIs `__. + location_id (str): + Optional. Cloud region where annotation should take place. + Supported cloud regions are: ``us-east1``, ``us-west1``, + ``europe-west1``, ``asia-east1``. If no region is specified, + the region will be determined based on video file location. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + input_content = proto.Field( + proto.BYTES, + number=6, + ) + features = proto.RepeatedField( + proto.ENUM, + number=2, + enum='Feature', + ) + video_context = proto.Field( + proto.MESSAGE, + number=3, + message='VideoContext', + ) + output_uri = proto.Field( + proto.STRING, + number=4, + ) + location_id = proto.Field( + proto.STRING, + number=5, + ) + + +class VideoContext(proto.Message): + r"""Video context and/or feature-specific parameters. + + Attributes: + segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): + Video segments to annotate. The segments may + overlap and are not required to be contiguous or + span the whole video. If unspecified, each video + is treated as a single segment. + label_detection_config (google.cloud.videointelligence_v1p3beta1.types.LabelDetectionConfig): + Config for LABEL_DETECTION. + shot_change_detection_config (google.cloud.videointelligence_v1p3beta1.types.ShotChangeDetectionConfig): + Config for SHOT_CHANGE_DETECTION. + explicit_content_detection_config (google.cloud.videointelligence_v1p3beta1.types.ExplicitContentDetectionConfig): + Config for EXPLICIT_CONTENT_DETECTION. + face_detection_config (google.cloud.videointelligence_v1p3beta1.types.FaceDetectionConfig): + Config for FACE_DETECTION. + speech_transcription_config (google.cloud.videointelligence_v1p3beta1.types.SpeechTranscriptionConfig): + Config for SPEECH_TRANSCRIPTION. + text_detection_config (google.cloud.videointelligence_v1p3beta1.types.TextDetectionConfig): + Config for TEXT_DETECTION. + person_detection_config (google.cloud.videointelligence_v1p3beta1.types.PersonDetectionConfig): + Config for PERSON_DETECTION. + object_tracking_config (google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingConfig): + Config for OBJECT_TRACKING. + """ + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + label_detection_config = proto.Field( + proto.MESSAGE, + number=2, + message='LabelDetectionConfig', + ) + shot_change_detection_config = proto.Field( + proto.MESSAGE, + number=3, + message='ShotChangeDetectionConfig', + ) + explicit_content_detection_config = proto.Field( + proto.MESSAGE, + number=4, + message='ExplicitContentDetectionConfig', + ) + face_detection_config = proto.Field( + proto.MESSAGE, + number=5, + message='FaceDetectionConfig', + ) + speech_transcription_config = proto.Field( + proto.MESSAGE, + number=6, + message='SpeechTranscriptionConfig', + ) + text_detection_config = proto.Field( + proto.MESSAGE, + number=8, + message='TextDetectionConfig', + ) + person_detection_config = proto.Field( + proto.MESSAGE, + number=11, + message='PersonDetectionConfig', + ) + object_tracking_config = proto.Field( + proto.MESSAGE, + number=13, + message='ObjectTrackingConfig', + ) + + +class LabelDetectionConfig(proto.Message): + r"""Config for LABEL_DETECTION. + + Attributes: + label_detection_mode (google.cloud.videointelligence_v1p3beta1.types.LabelDetectionMode): + What labels should be detected with LABEL_DETECTION, in + addition to video-level labels or segment-level labels. If + unspecified, defaults to ``SHOT_MODE``. + stationary_camera (bool): + Whether the video has been shot from a stationary (i.e., + non-moving) camera. When set to true, might improve + detection accuracy for moving objects. Should be used with + ``SHOT_AND_FRAME_MODE`` enabled. + model (str): + Model to use for label detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + frame_confidence_threshold (float): + The confidence threshold we perform filtering on the labels + from frame-level detection. If not set, it is set to 0.4 by + default. The valid range for this threshold is [0.1, 0.9]. + Any value set outside of this range will be clipped. Note: + For best results, follow the default threshold. We will + update the default threshold everytime when we release a new + model. + video_confidence_threshold (float): + The confidence threshold we perform filtering on the labels + from video-level and shot-level detections. If not set, it's + set to 0.3 by default. The valid range for this threshold is + [0.1, 0.9]. Any value set outside of this range will be + clipped. Note: For best results, follow the default + threshold. We will update the default threshold everytime + when we release a new model. + """ + + label_detection_mode = proto.Field( + proto.ENUM, + number=1, + enum='LabelDetectionMode', + ) + stationary_camera = proto.Field( + proto.BOOL, + number=2, + ) + model = proto.Field( + proto.STRING, + number=3, + ) + frame_confidence_threshold = proto.Field( + proto.FLOAT, + number=4, + ) + video_confidence_threshold = proto.Field( + proto.FLOAT, + number=5, + ) + + +class ShotChangeDetectionConfig(proto.Message): + r"""Config for SHOT_CHANGE_DETECTION. + + Attributes: + model (str): + Model to use for shot change detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class ObjectTrackingConfig(proto.Message): + r"""Config for OBJECT_TRACKING. + + Attributes: + model (str): + Model to use for object tracking. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class ExplicitContentDetectionConfig(proto.Message): + r"""Config for EXPLICIT_CONTENT_DETECTION. + + Attributes: + model (str): + Model to use for explicit content detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + + +class FaceDetectionConfig(proto.Message): + r"""Config for FACE_DETECTION. + + Attributes: + model (str): + Model to use for face detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + include_bounding_boxes (bool): + Whether bounding boxes are included in the + face annotation output. + include_attributes (bool): + Whether to enable face attributes detection, such as + glasses, dark_glasses, mouth_open etc. Ignored if + 'include_bounding_boxes' is set to false. + """ + + model = proto.Field( + proto.STRING, + number=1, + ) + include_bounding_boxes = proto.Field( + proto.BOOL, + number=2, + ) + include_attributes = proto.Field( + proto.BOOL, + number=5, + ) + + +class PersonDetectionConfig(proto.Message): + r"""Config for PERSON_DETECTION. + + Attributes: + include_bounding_boxes (bool): + Whether bounding boxes are included in the + person detection annotation output. + include_pose_landmarks (bool): + Whether to enable pose landmarks detection. Ignored if + 'include_bounding_boxes' is set to false. + include_attributes (bool): + Whether to enable person attributes detection, such as cloth + color (black, blue, etc), type (coat, dress, etc), pattern + (plain, floral, etc), hair, etc. Ignored if + 'include_bounding_boxes' is set to false. + """ + + include_bounding_boxes = proto.Field( + proto.BOOL, + number=1, + ) + include_pose_landmarks = proto.Field( + proto.BOOL, + number=2, + ) + include_attributes = proto.Field( + proto.BOOL, + number=3, + ) + + +class TextDetectionConfig(proto.Message): + r"""Config for TEXT_DETECTION. + + Attributes: + language_hints (Sequence[str]): + Language hint can be specified if the + language to be detected is known a priori. It + can increase the accuracy of the detection. + Language hint must be language code in BCP-47 + format. + + Automatic language detection is performed if no + hint is provided. + model (str): + Model to use for text detection. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + language_hints = proto.RepeatedField( + proto.STRING, + number=1, + ) + model = proto.Field( + proto.STRING, + number=2, + ) + + +class VideoSegment(proto.Message): + r"""Video segment. + + Attributes: + start_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the start of the segment + (inclusive). + end_time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the end of the segment + (inclusive). + """ + + start_time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class LabelSegment(proto.Message): + r"""Video segment level annotation results for label detection. + + Attributes: + segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): + Video segment where a label was detected. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class LabelFrame(proto.Message): + r"""Video frame level annotation results for label detection. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + confidence (float): + Confidence that the label is accurate. Range: [0, 1]. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + +class Entity(proto.Message): + r"""Detected entity from video analysis. + + Attributes: + entity_id (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + description (str): + Textual description, e.g., ``Fixed-gear bicycle``. + language_code (str): + Language code for ``description`` in BCP-47 format. + """ + + entity_id = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class LabelAnnotation(proto.Message): + r"""Label annotation. + + Attributes: + entity (google.cloud.videointelligence_v1p3beta1.types.Entity): + Detected entity. + category_entities (Sequence[google.cloud.videointelligence_v1p3beta1.types.Entity]): + Common categories for the detected entity. For example, when + the label is ``Terrier``, the category is likely ``dog``. + And in some cases there might be more than one categories + e.g., ``Terrier`` could also be a ``pet``. + segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelSegment]): + All video segments where a label was + detected. + frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelFrame]): + All video frames where a label was detected. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + category_entities = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Entity', + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelSegment', + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelFrame', + ) + + +class ExplicitContentFrame(proto.Message): + r"""Video frame level annotation results for explicit content. + + Attributes: + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + location. + pornography_likelihood (google.cloud.videointelligence_v1p3beta1.types.Likelihood): + Likelihood of the pornography content.. + """ + + time_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + pornography_likelihood = proto.Field( + proto.ENUM, + number=2, + enum='Likelihood', + ) + + +class ExplicitContentAnnotation(proto.Message): + r"""Explicit content annotation (based on per-frame visual + signals only). If no explicit content has been detected in a + frame, no annotations are present for that frame. + + Attributes: + frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.ExplicitContentFrame]): + All video frames where explicit content was + detected. + """ + + frames = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExplicitContentFrame', + ) + + +class NormalizedBoundingBox(proto.Message): + r"""Normalized bounding box. The normalized vertex coordinates are + relative to the original image. Range: [0, 1]. + + Attributes: + left (float): + Left X coordinate. + top (float): + Top Y coordinate. + right (float): + Right X coordinate. + bottom (float): + Bottom Y coordinate. + """ + + left = proto.Field( + proto.FLOAT, + number=1, + ) + top = proto.Field( + proto.FLOAT, + number=2, + ) + right = proto.Field( + proto.FLOAT, + number=3, + ) + bottom = proto.Field( + proto.FLOAT, + number=4, + ) + + +class TimestampedObject(proto.Message): + r"""For tracking related features. An object at time_offset with + attributes, and located with normalized_bounding_box. + + Attributes: + normalized_bounding_box (google.cloud.videointelligence_v1p3beta1.types.NormalizedBoundingBox): + Normalized Bounding box in a frame, where the + object is located. + time_offset (google.protobuf.duration_pb2.Duration): + Time-offset, relative to the beginning of the + video, corresponding to the video frame for this + object. + attributes (Sequence[google.cloud.videointelligence_v1p3beta1.types.DetectedAttribute]): + Optional. The attributes of the object in the + bounding box. + landmarks (Sequence[google.cloud.videointelligence_v1p3beta1.types.DetectedLandmark]): + Optional. The detected landmarks. + """ + + normalized_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingBox', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + attributes = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='DetectedAttribute', + ) + landmarks = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='DetectedLandmark', + ) + + +class Track(proto.Message): + r"""A track of an object instance. + + Attributes: + segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): + Video segment of a track. + timestamped_objects (Sequence[google.cloud.videointelligence_v1p3beta1.types.TimestampedObject]): + The object with timestamp and attributes per + frame in the track. + attributes (Sequence[google.cloud.videointelligence_v1p3beta1.types.DetectedAttribute]): + Optional. Attributes in the track level. + confidence (float): + Optional. The confidence score of the tracked + object. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + timestamped_objects = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TimestampedObject', + ) + attributes = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='DetectedAttribute', + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + +class DetectedAttribute(proto.Message): + r"""A generic detected attribute represented by name in string + format. + + Attributes: + name (str): + The name of the attribute, for example, glasses, + dark_glasses, mouth_open. A full list of supported type + names will be provided in the document. + confidence (float): + Detected attribute confidence. Range [0, 1]. + value (str): + Text value of the detection result. For + example, the value for "HairColor" can be + "black", "blonde", etc. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + value = proto.Field( + proto.STRING, + number=3, + ) + + +class Celebrity(proto.Message): + r"""Celebrity definition. + + Attributes: + name (str): + The resource name of the celebrity. Have the format + ``video-intelligence/kg-mid`` indicates a celebrity from + preloaded gallery. kg-mid is the id in Google knowledge + graph, which is unique for the celebrity. + display_name (str): + The celebrity name. + description (str): + Textual description of additional information + about the celebrity, if applicable. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + + +class CelebrityTrack(proto.Message): + r"""The annotation result of a celebrity face track. + RecognizedCelebrity field could be empty if the face track does + not have any matched celebrities. + + Attributes: + celebrities (Sequence[google.cloud.videointelligence_v1p3beta1.types.CelebrityTrack.RecognizedCelebrity]): + Top N match of the celebrities for the face + in this track. + face_track (google.cloud.videointelligence_v1p3beta1.types.Track): + A track of a person's face. + """ + + class RecognizedCelebrity(proto.Message): + r"""The recognized celebrity with confidence score. + + Attributes: + celebrity (google.cloud.videointelligence_v1p3beta1.types.Celebrity): + The recognized celebrity. + confidence (float): + Recognition confidence. Range [0, 1]. + """ + + celebrity = proto.Field( + proto.MESSAGE, + number=1, + message='Celebrity', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + + celebrities = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RecognizedCelebrity, + ) + face_track = proto.Field( + proto.MESSAGE, + number=3, + message='Track', + ) + + +class CelebrityRecognitionAnnotation(proto.Message): + r"""Celebrity recognition annotation per video. + + Attributes: + celebrity_tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.CelebrityTrack]): + The tracks detected from the input video, + including recognized celebrities and other + detected faces in the video. + """ + + celebrity_tracks = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CelebrityTrack', + ) + + +class DetectedLandmark(proto.Message): + r"""A generic detected landmark represented by name in string + format and a 2D location. + + Attributes: + name (str): + The name of this landmark, for example, left_hand, + right_shoulder. + point (google.cloud.videointelligence_v1p3beta1.types.NormalizedVertex): + The 2D point of the detected landmark using + the normalized image coordindate system. The + normalized coordinates have the range from 0 to + 1. + confidence (float): + The confidence score of the detected landmark. Range [0, 1]. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + point = proto.Field( + proto.MESSAGE, + number=2, + message='NormalizedVertex', + ) + confidence = proto.Field( + proto.FLOAT, + number=3, + ) + + +class FaceDetectionAnnotation(proto.Message): + r"""Face detection annotation. + + Attributes: + tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): + The face tracks with attributes. + thumbnail (bytes): + The thumbnail of a person's face. + """ + + tracks = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Track', + ) + thumbnail = proto.Field( + proto.BYTES, + number=4, + ) + + +class PersonDetectionAnnotation(proto.Message): + r"""Person detection annotation per video. + + Attributes: + tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): + The detected tracks of a person. + """ + + tracks = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Track', + ) + + +class VideoAnnotationResults(proto.Message): + r"""Annotation results for a single video. + + Attributes: + input_uri (str): + Video file location in `Cloud + Storage `__. + segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): + Video segment on which the annotation is run. + segment_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): + Topical label annotations on video level or + user-specified segment level. There is exactly + one element for each unique label. + segment_presence_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): + Presence label annotations on video level or user-specified + segment level. There is exactly one element for each unique + label. Compared to the existing topical + ``segment_label_annotations``, this field presents more + fine-grained, segment-level labels detected in video content + and is made available only when the client sets + ``LabelDetectionConfig.model`` to "builtin/latest" in the + request. + shot_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): + Topical label annotations on shot level. + There is exactly one element for each unique + label. + shot_presence_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): + Presence label annotations on shot level. There is exactly + one element for each unique label. Compared to the existing + topical ``shot_label_annotations``, this field presents more + fine-grained, shot-level labels detected in video content + and is made available only when the client sets + ``LabelDetectionConfig.model`` to "builtin/latest" in the + request. + frame_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): + Label annotations on frame level. + There is exactly one element for each unique + label. + face_detection_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.FaceDetectionAnnotation]): + Face detection annotations. + shot_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): + Shot annotations. Each shot is represented as + a video segment. + explicit_annotation (google.cloud.videointelligence_v1p3beta1.types.ExplicitContentAnnotation): + Explicit content annotation. + speech_transcriptions (Sequence[google.cloud.videointelligence_v1p3beta1.types.SpeechTranscription]): + Speech transcription. + text_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.TextAnnotation]): + OCR text detection and tracking. + Annotations for list of detected text snippets. + Each will have list of frame information + associated with it. + object_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingAnnotation]): + Annotations for list of objects detected and + tracked in video. + logo_recognition_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LogoRecognitionAnnotation]): + Annotations for list of logos detected, + tracked and recognized in video. + person_detection_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.PersonDetectionAnnotation]): + Person detection annotations. + celebrity_recognition_annotations (google.cloud.videointelligence_v1p3beta1.types.CelebrityRecognitionAnnotation): + Celebrity recognition annotations. + error (google.rpc.status_pb2.Status): + If set, indicates an error. Note that for a single + ``AnnotateVideoRequest`` some videos may succeed and some + may fail. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + segment = proto.Field( + proto.MESSAGE, + number=10, + message='VideoSegment', + ) + segment_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='LabelAnnotation', + ) + segment_presence_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=23, + message='LabelAnnotation', + ) + shot_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='LabelAnnotation', + ) + shot_presence_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=24, + message='LabelAnnotation', + ) + frame_label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='LabelAnnotation', + ) + face_detection_annotations = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='FaceDetectionAnnotation', + ) + shot_annotations = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='VideoSegment', + ) + explicit_annotation = proto.Field( + proto.MESSAGE, + number=7, + message='ExplicitContentAnnotation', + ) + speech_transcriptions = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='SpeechTranscription', + ) + text_annotations = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='TextAnnotation', + ) + object_annotations = proto.RepeatedField( + proto.MESSAGE, + number=14, + message='ObjectTrackingAnnotation', + ) + logo_recognition_annotations = proto.RepeatedField( + proto.MESSAGE, + number=19, + message='LogoRecognitionAnnotation', + ) + person_detection_annotations = proto.RepeatedField( + proto.MESSAGE, + number=20, + message='PersonDetectionAnnotation', + ) + celebrity_recognition_annotations = proto.Field( + proto.MESSAGE, + number=21, + message='CelebrityRecognitionAnnotation', + ) + error = proto.Field( + proto.MESSAGE, + number=9, + message=status_pb2.Status, + ) + + +class AnnotateVideoResponse(proto.Message): + r"""Video annotation response. Included in the ``response`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_results (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoAnnotationResults]): + Annotation results for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationResults', + ) + + +class VideoAnnotationProgress(proto.Message): + r"""Annotation progress for a single video. + + Attributes: + input_uri (str): + Video file location in `Cloud + Storage `__. + progress_percent (int): + Approximate percentage processed thus far. + Guaranteed to be 100 when fully processed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the request was received. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Time of the most recent update. + feature (google.cloud.videointelligence_v1p3beta1.types.Feature): + Specifies which feature is being tracked if + the request contains more than one feature. + segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): + Specifies which segment is being tracked if + the request contains more than one segment. + """ + + input_uri = proto.Field( + proto.STRING, + number=1, + ) + progress_percent = proto.Field( + proto.INT32, + number=2, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + feature = proto.Field( + proto.ENUM, + number=5, + enum='Feature', + ) + segment = proto.Field( + proto.MESSAGE, + number=6, + message='VideoSegment', + ) + + +class AnnotateVideoProgress(proto.Message): + r"""Video annotation progress. Included in the ``metadata`` field of the + ``Operation`` returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + annotation_progress (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoAnnotationProgress]): + Progress metadata for all videos specified in + ``AnnotateVideoRequest``. + """ + + annotation_progress = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoAnnotationProgress', + ) + + +class SpeechTranscriptionConfig(proto.Message): + r"""Config for SPEECH_TRANSCRIPTION. + + Attributes: + language_code (str): + Required. *Required* The language of the supplied audio as a + `BCP-47 `__ + language tag. Example: "en-US". See `Language + Support `__ + for a list of the currently supported language codes. + max_alternatives (int): + Optional. Maximum number of recognition hypotheses to be + returned. Specifically, the maximum number of + ``SpeechRecognitionAlternative`` messages within each + ``SpeechTranscription``. The server may return fewer than + ``max_alternatives``. Valid values are ``0``-``30``. A value + of ``0`` or ``1`` will return a maximum of one. If omitted, + will return a maximum of one. + filter_profanity (bool): + Optional. If set to ``true``, the server will attempt to + filter out profanities, replacing all but the initial + character in each filtered word with asterisks, e.g. "f***". + If set to ``false`` or omitted, profanities won't be + filtered out. + speech_contexts (Sequence[google.cloud.videointelligence_v1p3beta1.types.SpeechContext]): + Optional. A means to provide context to + assist the speech recognition. + enable_automatic_punctuation (bool): + Optional. If 'true', adds punctuation to + recognition result hypotheses. This feature is + only available in select languages. Setting this + for requests in other languages has no effect at + all. The default 'false' value does not add + punctuation to result hypotheses. NOTE: "This is + currently offered as an experimental service, + complimentary to all users. In the future this + may be exclusively available as a premium + feature.". + audio_tracks (Sequence[int]): + Optional. For file formats, such as MXF or + MKV, supporting multiple audio tracks, specify + up to two tracks. Default: track 0. + enable_speaker_diarization (bool): + Optional. If 'true', enables speaker detection for each + recognized word in the top alternative of the recognition + result using a speaker_tag provided in the WordInfo. Note: + When this is true, we send all the words from the beginning + of the audio for the top alternative in every consecutive + response. This is done in order to improve our speaker tags + as our models learn to identify the speakers in the + conversation over time. + diarization_speaker_count (int): + Optional. If set, specifies the estimated number of speakers + in the conversation. If not set, defaults to '2'. Ignored + unless enable_speaker_diarization is set to true. + enable_word_confidence (bool): + Optional. If ``true``, the top result includes a list of + words and the confidence for those words. If ``false``, no + word-level confidence information is returned. The default + is ``false``. + """ + + language_code = proto.Field( + proto.STRING, + number=1, + ) + max_alternatives = proto.Field( + proto.INT32, + number=2, + ) + filter_profanity = proto.Field( + proto.BOOL, + number=3, + ) + speech_contexts = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='SpeechContext', + ) + enable_automatic_punctuation = proto.Field( + proto.BOOL, + number=5, + ) + audio_tracks = proto.RepeatedField( + proto.INT32, + number=6, + ) + enable_speaker_diarization = proto.Field( + proto.BOOL, + number=7, + ) + diarization_speaker_count = proto.Field( + proto.INT32, + number=8, + ) + enable_word_confidence = proto.Field( + proto.BOOL, + number=9, + ) + + +class SpeechContext(proto.Message): + r"""Provides "hints" to the speech recognizer to favor specific + words and phrases in the results. + + Attributes: + phrases (Sequence[str]): + Optional. A list of strings containing words and phrases + "hints" so that the speech recognition is more likely to + recognize them. This can be used to improve the accuracy for + specific words and phrases, for example, if specific + commands are typically spoken by the user. This can also be + used to add additional words to the vocabulary of the + recognizer. See `usage + limits `__. + """ + + phrases = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class SpeechTranscription(proto.Message): + r"""A speech recognition result corresponding to a portion of the + audio. + + Attributes: + alternatives (Sequence[google.cloud.videointelligence_v1p3beta1.types.SpeechRecognitionAlternative]): + May contain one or more recognition hypotheses (up to the + maximum specified in ``max_alternatives``). These + alternatives are ordered in terms of accuracy, with the top + (first) alternative being the most probable, as ranked by + the recognizer. + language_code (str): + Output only. The + `BCP-47 `__ + language tag of the language in this result. This language + code was detected to have the most likelihood of being + spoken in the audio. + """ + + alternatives = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SpeechRecognitionAlternative', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class SpeechRecognitionAlternative(proto.Message): + r"""Alternative hypotheses (a.k.a. n-best list). + + Attributes: + transcript (str): + Transcript text representing the words that + the user spoke. + confidence (float): + Output only. The confidence estimate between 0.0 and 1.0. A + higher number indicates an estimated greater likelihood that + the recognized words are correct. This field is set only for + the top alternative. This field is not guaranteed to be + accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + words (Sequence[google.cloud.videointelligence_v1p3beta1.types.WordInfo]): + Output only. A list of word-specific information for each + recognized word. Note: When ``enable_speaker_diarization`` + is set to true, you will see all the words from the + beginning of the audio. + """ + + transcript = proto.Field( + proto.STRING, + number=1, + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + words = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='WordInfo', + ) + + +class WordInfo(proto.Message): + r"""Word-specific information for recognized words. Word information is + only included in the response when certain request parameters are + set, such as ``enable_word_time_offsets``. + + Attributes: + start_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the start of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + end_time (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the audio, and + corresponding to the end of the spoken word. This field is + only set if ``enable_word_time_offsets=true`` and only in + the top hypothesis. This is an experimental feature and the + accuracy of the time offset can vary. + word (str): + The word corresponding to this set of + information. + confidence (float): + Output only. The confidence estimate between 0.0 and 1.0. A + higher number indicates an estimated greater likelihood that + the recognized words are correct. This field is set only for + the top alternative. This field is not guaranteed to be + accurate and users should not rely on it to be always + provided. The default of 0.0 is a sentinel value indicating + ``confidence`` was not set. + speaker_tag (int): + Output only. A distinct integer value is assigned for every + speaker within the audio. This field specifies which one of + those speakers was detected to have spoken this word. Value + ranges from 1 up to diarization_speaker_count, and is only + set if speaker diarization is enabled. + """ + + start_time = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + word = proto.Field( + proto.STRING, + number=3, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + speaker_tag = proto.Field( + proto.INT32, + number=5, + ) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field( + proto.FLOAT, + number=1, + ) + y = proto.Field( + proto.FLOAT, + number=2, + ) + + +class NormalizedBoundingPoly(proto.Message): + r"""Normalized bounding polygon for text (that might not be aligned with + axis). Contains list of the corner points in clockwise order + starting from top-left corner. For example, for a rectangular + bounding box: When the text is horizontal it might look like: 0----1 + \| \| 3----2 + + When it's clockwise rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 + + and the vertex order will still be (0, 1, 2, 3). Note that values + can be less than 0, or greater than 1 due to trignometric + calculations for location of the box. + + Attributes: + vertices (Sequence[google.cloud.videointelligence_v1p3beta1.types.NormalizedVertex]): + Normalized vertices of the bounding polygon. + """ + + vertices = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='NormalizedVertex', + ) + + +class TextSegment(proto.Message): + r"""Video segment level annotation results for text detection. + + Attributes: + segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): + Video segment where a text snippet was + detected. + confidence (float): + Confidence for the track of detected text. It + is calculated as the highest over all frames + where OCR detected text appears. + frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.TextFrame]): + Information related to the frames where OCR + detected text appears. + """ + + segment = proto.Field( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + confidence = proto.Field( + proto.FLOAT, + number=2, + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='TextFrame', + ) + + +class TextFrame(proto.Message): + r"""Video frame level annotation results for text annotation + (OCR). Contains information regarding timestamp and bounding box + locations for the frames containing detected OCR text snippets. + + Attributes: + rotated_bounding_box (google.cloud.videointelligence_v1p3beta1.types.NormalizedBoundingPoly): + Bounding polygon of the detected text for + this frame. + time_offset (google.protobuf.duration_pb2.Duration): + Timestamp of this frame. + """ + + rotated_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingPoly', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class TextAnnotation(proto.Message): + r"""Annotations related to one detected OCR text snippet. This + will contain the corresponding text, confidence value, and frame + level information for each detection. + + Attributes: + text (str): + The detected text. + segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.TextSegment]): + All video segments where OCR detected text + appears. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TextSegment', + ) + + +class ObjectTrackingFrame(proto.Message): + r"""Video frame level annotations for object detection and + tracking. This field stores per frame location, time offset, and + confidence. + + Attributes: + normalized_bounding_box (google.cloud.videointelligence_v1p3beta1.types.NormalizedBoundingBox): + The normalized bounding box location of this + object track for the frame. + time_offset (google.protobuf.duration_pb2.Duration): + The timestamp of the frame in microseconds. + """ + + normalized_bounding_box = proto.Field( + proto.MESSAGE, + number=1, + message='NormalizedBoundingBox', + ) + time_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ObjectTrackingAnnotation(proto.Message): + r"""Annotations corresponding to one tracked object. + + Attributes: + segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): + Non-streaming batch mode ONLY. + Each object track corresponds to one video + segment where it appears. + track_id (int): + Streaming mode ONLY. In streaming mode, we do not know the + end time of a tracked object before it is completed. Hence, + there is no VideoSegment info returned. Instead, we provide + a unique identifiable integer track_id so that the customers + can correlate the results of the ongoing + ObjectTrackAnnotation of the same track_id over time. + entity (google.cloud.videointelligence_v1p3beta1.types.Entity): + Entity to specify the object category that + this track is labeled as. + confidence (float): + Object category's labeling confidence of this + track. + frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingFrame]): + Information corresponding to all frames where + this object track appears. Non-streaming batch + mode: it may be one or multiple + ObjectTrackingFrame messages in frames. + Streaming mode: it can only be one + ObjectTrackingFrame message in frames. + """ + + segment = proto.Field( + proto.MESSAGE, + number=3, + oneof='track_info', + message='VideoSegment', + ) + track_id = proto.Field( + proto.INT64, + number=5, + oneof='track_info', + ) + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + frames = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ObjectTrackingFrame', + ) + + +class LogoRecognitionAnnotation(proto.Message): + r"""Annotation corresponding to one detected, tracked and + recognized logo class. + + Attributes: + entity (google.cloud.videointelligence_v1p3beta1.types.Entity): + Entity category information to specify the + logo class that all the logo tracks within this + LogoRecognitionAnnotation are recognized as. + tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): + All logo tracks where the recognized logo + appears. Each track corresponds to one logo + instance appearing in consecutive frames. + segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): + All video segments where the recognized logo + appears. There might be multiple instances of + the same logo class appearing in one + VideoSegment. + """ + + entity = proto.Field( + proto.MESSAGE, + number=1, + message='Entity', + ) + tracks = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Track', + ) + segments = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='VideoSegment', + ) + + +class StreamingAnnotateVideoRequest(proto.Message): + r"""The top-level message sent by the client for the + ``StreamingAnnotateVideo`` method. Multiple + ``StreamingAnnotateVideoRequest`` messages are sent. The first + message must only contain a ``StreamingVideoConfig`` message. All + subsequent messages must only contain ``input_content`` data. + + Attributes: + video_config (google.cloud.videointelligence_v1p3beta1.types.StreamingVideoConfig): + Provides information to the annotator, specifing how to + process the request. The first + ``AnnotateStreamingVideoRequest`` message must only contain + a ``video_config`` message. + input_content (bytes): + The video data to be annotated. Chunks of video data are + sequentially sent in ``StreamingAnnotateVideoRequest`` + messages. Except the initial + ``StreamingAnnotateVideoRequest`` message containing only + ``video_config``, all subsequent + ``AnnotateStreamingVideoRequest`` messages must only contain + ``input_content`` field. Note: as with all bytes fields, + protobuffers use a pure binary representation (not base64). + """ + + video_config = proto.Field( + proto.MESSAGE, + number=1, + oneof='streaming_request', + message='StreamingVideoConfig', + ) + input_content = proto.Field( + proto.BYTES, + number=2, + oneof='streaming_request', + ) + + +class StreamingVideoConfig(proto.Message): + r"""Provides information to the annotator that specifies how to + process the request. + + Attributes: + shot_change_detection_config (google.cloud.videointelligence_v1p3beta1.types.StreamingShotChangeDetectionConfig): + Config for STREAMING_SHOT_CHANGE_DETECTION. + label_detection_config (google.cloud.videointelligence_v1p3beta1.types.StreamingLabelDetectionConfig): + Config for STREAMING_LABEL_DETECTION. + explicit_content_detection_config (google.cloud.videointelligence_v1p3beta1.types.StreamingExplicitContentDetectionConfig): + Config for STREAMING_EXPLICIT_CONTENT_DETECTION. + object_tracking_config (google.cloud.videointelligence_v1p3beta1.types.StreamingObjectTrackingConfig): + Config for STREAMING_OBJECT_TRACKING. + automl_action_recognition_config (google.cloud.videointelligence_v1p3beta1.types.StreamingAutomlActionRecognitionConfig): + Config for STREAMING_AUTOML_ACTION_RECOGNITION. + automl_classification_config (google.cloud.videointelligence_v1p3beta1.types.StreamingAutomlClassificationConfig): + Config for STREAMING_AUTOML_CLASSIFICATION. + automl_object_tracking_config (google.cloud.videointelligence_v1p3beta1.types.StreamingAutomlObjectTrackingConfig): + Config for STREAMING_AUTOML_OBJECT_TRACKING. + feature (google.cloud.videointelligence_v1p3beta1.types.StreamingFeature): + Requested annotation feature. + storage_config (google.cloud.videointelligence_v1p3beta1.types.StreamingStorageConfig): + Streaming storage option. By default: storage + is disabled. + """ + + shot_change_detection_config = proto.Field( + proto.MESSAGE, + number=2, + oneof='streaming_config', + message='StreamingShotChangeDetectionConfig', + ) + label_detection_config = proto.Field( + proto.MESSAGE, + number=3, + oneof='streaming_config', + message='StreamingLabelDetectionConfig', + ) + explicit_content_detection_config = proto.Field( + proto.MESSAGE, + number=4, + oneof='streaming_config', + message='StreamingExplicitContentDetectionConfig', + ) + object_tracking_config = proto.Field( + proto.MESSAGE, + number=5, + oneof='streaming_config', + message='StreamingObjectTrackingConfig', + ) + automl_action_recognition_config = proto.Field( + proto.MESSAGE, + number=23, + oneof='streaming_config', + message='StreamingAutomlActionRecognitionConfig', + ) + automl_classification_config = proto.Field( + proto.MESSAGE, + number=21, + oneof='streaming_config', + message='StreamingAutomlClassificationConfig', + ) + automl_object_tracking_config = proto.Field( + proto.MESSAGE, + number=22, + oneof='streaming_config', + message='StreamingAutomlObjectTrackingConfig', + ) + feature = proto.Field( + proto.ENUM, + number=1, + enum='StreamingFeature', + ) + storage_config = proto.Field( + proto.MESSAGE, + number=30, + message='StreamingStorageConfig', + ) + + +class StreamingAnnotateVideoResponse(proto.Message): + r"""``StreamingAnnotateVideoResponse`` is the only message returned to + the client by ``StreamingAnnotateVideo``. A series of zero or more + ``StreamingAnnotateVideoResponse`` messages are streamed back to the + client. + + Attributes: + error (google.rpc.status_pb2.Status): + If set, returns a [google.rpc.Status][google.rpc.Status] + message that specifies the error for the operation. + annotation_results (google.cloud.videointelligence_v1p3beta1.types.StreamingVideoAnnotationResults): + Streaming annotation results. + annotation_results_uri (str): + Google Cloud Storage(GCS) URI that stores annotation results + of one streaming session in JSON format. It is the + annotation_result_storage_directory from the request + followed by '/cloud_project_number-session_id'. + """ + + error = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + annotation_results = proto.Field( + proto.MESSAGE, + number=2, + message='StreamingVideoAnnotationResults', + ) + annotation_results_uri = proto.Field( + proto.STRING, + number=3, + ) + + +class StreamingVideoAnnotationResults(proto.Message): + r"""Streaming annotation results corresponding to a portion of + the video that is currently being processed. + + Attributes: + shot_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): + Shot annotation results. Each shot is + represented as a video segment. + label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): + Label annotation results. + explicit_annotation (google.cloud.videointelligence_v1p3beta1.types.ExplicitContentAnnotation): + Explicit content annotation results. + object_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingAnnotation]): + Object tracking results. + """ + + shot_annotations = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VideoSegment', + ) + label_annotations = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='LabelAnnotation', + ) + explicit_annotation = proto.Field( + proto.MESSAGE, + number=3, + message='ExplicitContentAnnotation', + ) + object_annotations = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='ObjectTrackingAnnotation', + ) + + +class StreamingShotChangeDetectionConfig(proto.Message): + r"""Config for STREAMING_SHOT_CHANGE_DETECTION. + """ + + +class StreamingLabelDetectionConfig(proto.Message): + r"""Config for STREAMING_LABEL_DETECTION. + + Attributes: + stationary_camera (bool): + Whether the video has been captured from a + stationary (i.e. non-moving) camera. When set to + true, might improve detection accuracy for + moving objects. Default: false. + """ + + stationary_camera = proto.Field( + proto.BOOL, + number=1, + ) + + +class StreamingExplicitContentDetectionConfig(proto.Message): + r"""Config for STREAMING_EXPLICIT_CONTENT_DETECTION. + """ + + +class StreamingObjectTrackingConfig(proto.Message): + r"""Config for STREAMING_OBJECT_TRACKING. + """ + + +class StreamingAutomlActionRecognitionConfig(proto.Message): + r"""Config for STREAMING_AUTOML_ACTION_RECOGNITION. + + Attributes: + model_name (str): + Resource name of AutoML model. Format: + ``projects/{project_id}/locations/{location_id}/models/{model_id}`` + """ + + model_name = proto.Field( + proto.STRING, + number=1, + ) + + +class StreamingAutomlClassificationConfig(proto.Message): + r"""Config for STREAMING_AUTOML_CLASSIFICATION. + + Attributes: + model_name (str): + Resource name of AutoML model. Format: + ``projects/{project_number}/locations/{location_id}/models/{model_id}`` + """ + + model_name = proto.Field( + proto.STRING, + number=1, + ) + + +class StreamingAutomlObjectTrackingConfig(proto.Message): + r"""Config for STREAMING_AUTOML_OBJECT_TRACKING. + + Attributes: + model_name (str): + Resource name of AutoML model. Format: + ``projects/{project_id}/locations/{location_id}/models/{model_id}`` + """ + + model_name = proto.Field( + proto.STRING, + number=1, + ) + + +class StreamingStorageConfig(proto.Message): + r"""Config for streaming storage option. + + Attributes: + enable_storage_annotation_result (bool): + Enable streaming storage. Default: false. + annotation_result_storage_directory (str): + Cloud Storage URI to store all annotation results for one + client. Client should specify this field as the top-level + storage directory. Annotation results of different sessions + will be put into different sub-directories denoted by + project_name and session_id. All sub-directories will be + auto generated by program and will be made accessible to + client in response proto. URIs must be specified in the + following format: ``gs://bucket-id/object-id`` ``bucket-id`` + should be a valid Cloud Storage bucket created by client and + bucket permission shall also be configured properly. + ``object-id`` can be arbitrary string that make sense to + client. Other URI formats will return error and cause Cloud + Storage write failure. + """ + + enable_storage_annotation_result = proto.Field( + proto.BOOL, + number=1, + ) + annotation_result_storage_directory = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p3beta1/mypy.ini b/owl-bot-staging/v1p3beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1p3beta1/noxfile.py b/owl-bot-staging/v1p3beta1/noxfile.py new file mode 100644 index 00000000..0fd4fd5a --- /dev/null +++ b/owl-bot-staging/v1p3beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/videointelligence_v1p3beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py b/owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py new file mode 100644 index 00000000..e172e7e2 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class videointelligenceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), + 'streaming_annotate_video': ('video_config', 'input_content', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=videointelligenceCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the videointelligence client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1p3beta1/setup.py b/owl-bot-staging/v1p3beta1/setup.py new file mode 100644 index 00000000..87b7ba3d --- /dev/null +++ b/owl-bot-staging/v1p3beta1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-videointelligence', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1p3beta1/tests/__init__.py b/owl-bot-staging/v1p3beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p3beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/__init__.py b/owl-bot-staging/v1p3beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p3beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py new file mode 100644 index 00000000..1205b87d --- /dev/null +++ b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py @@ -0,0 +1,1031 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceAsyncClient +from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service import transports +from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from google.oauth2 import service_account +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None + assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + StreamingVideoIntelligenceServiceClient, + StreamingVideoIntelligenceServiceAsyncClient, +]) +def test_streaming_video_intelligence_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), + (transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_streaming_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + StreamingVideoIntelligenceServiceClient, + StreamingVideoIntelligenceServiceAsyncClient, +]) +def test_streaming_video_intelligence_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_streaming_video_intelligence_service_client_get_transport_class(): + transport = StreamingVideoIntelligenceServiceClient.get_transport_class() + available_transports = [ + transports.StreamingVideoIntelligenceServiceGrpcTransport, + ] + assert transport in available_transports + + transport = StreamingVideoIntelligenceServiceClient.get_transport_class("grpc") + assert transport == transports.StreamingVideoIntelligenceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), + (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(StreamingVideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceClient)) +@mock.patch.object(StreamingVideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceAsyncClient)) +def test_streaming_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(StreamingVideoIntelligenceServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(StreamingVideoIntelligenceServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc", "true"), + (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc", "false"), + (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(StreamingVideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceClient)) +@mock.patch.object(StreamingVideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_streaming_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), + (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_streaming_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), + (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_streaming_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_streaming_video_intelligence_service_client_client_options_from_dict(): + with mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = StreamingVideoIntelligenceServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_streaming_annotate_video(transport: str = 'grpc', request_type=video_intelligence.StreamingAnnotateVideoRequest): + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([video_intelligence.StreamingAnnotateVideoResponse()]) + response = client.streaming_annotate_video(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, video_intelligence.StreamingAnnotateVideoResponse) + + +def test_streaming_annotate_video_from_dict(): + test_streaming_annotate_video(request_type=dict) + + +@pytest.mark.asyncio +async def test_streaming_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.StreamingAnnotateVideoRequest): + client = StreamingVideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.streaming_annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[video_intelligence.StreamingAnnotateVideoResponse()]) + response = await client.streaming_annotate_video(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, video_intelligence.StreamingAnnotateVideoResponse) + + +@pytest.mark.asyncio +async def test_streaming_annotate_video_async_from_dict(): + await test_streaming_annotate_video_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingVideoIntelligenceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StreamingVideoIntelligenceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StreamingVideoIntelligenceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.StreamingVideoIntelligenceServiceGrpcTransport, + transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.StreamingVideoIntelligenceServiceGrpcTransport, + ) + +def test_streaming_video_intelligence_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.StreamingVideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_streaming_video_intelligence_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.StreamingVideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'streaming_annotate_video', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +@requires_google_auth_gte_1_25_0 +def test_streaming_video_intelligence_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamingVideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_streaming_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamingVideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_streaming_video_intelligence_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.StreamingVideoIntelligenceServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_streaming_video_intelligence_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + StreamingVideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_streaming_video_intelligence_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + StreamingVideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamingVideoIntelligenceServiceGrpcTransport, + transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_streaming_video_intelligence_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StreamingVideoIntelligenceServiceGrpcTransport, + transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_streaming_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.StreamingVideoIntelligenceServiceGrpcTransport, grpc_helpers), + (transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_streaming_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "videointelligence.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="videointelligence.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.StreamingVideoIntelligenceServiceGrpcTransport, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_streaming_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_streaming_video_intelligence_service_host_no_port(): + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_streaming_video_intelligence_service_host_with_port(): + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:8000' + +def test_streaming_video_intelligence_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_streaming_video_intelligence_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.StreamingVideoIntelligenceServiceGrpcTransport, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_streaming_video_intelligence_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.StreamingVideoIntelligenceServiceGrpcTransport, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_streaming_video_intelligence_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = StreamingVideoIntelligenceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = StreamingVideoIntelligenceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingVideoIntelligenceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = StreamingVideoIntelligenceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = StreamingVideoIntelligenceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingVideoIntelligenceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = StreamingVideoIntelligenceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = StreamingVideoIntelligenceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingVideoIntelligenceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = StreamingVideoIntelligenceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = StreamingVideoIntelligenceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingVideoIntelligenceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = StreamingVideoIntelligenceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = StreamingVideoIntelligenceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = StreamingVideoIntelligenceServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.StreamingVideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.StreamingVideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = StreamingVideoIntelligenceServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = StreamingVideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py new file mode 100644 index 00000000..c00d82e2 --- /dev/null +++ b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py @@ -0,0 +1,1177 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient +from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service import VideoIntelligenceServiceClient +from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service import transports +from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.videointelligence_v1p3beta1.types import video_intelligence +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VideoIntelligenceServiceClient, + VideoIntelligenceServiceAsyncClient, +]) +def test_video_intelligence_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_client_get_transport_class(): + transport = VideoIntelligenceServiceClient.get_transport_class() + available_transports = [ + transports.VideoIntelligenceServiceGrpcTransport, + ] + assert transport in available_transports + + transport = VideoIntelligenceServiceClient.get_transport_class("grpc") + assert transport == transports.VideoIntelligenceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) +@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), + (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_video_intelligence_service_client_client_options_from_dict(): + with mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VideoIntelligenceServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_annotate_video_from_dict(): + test_annotate_video(request_type=dict) + + +def test_annotate_video_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + client.annotate_video() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + +@pytest.mark.asyncio +async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.annotate_video(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == video_intelligence.AnnotateVideoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_annotate_video_async_from_dict(): + await test_annotate_video_async(request_type=dict) + + +def test_annotate_video_flattened(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +def test_annotate_video_flattened_error(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.annotate_video), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.annotate_video( + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].input_uri == 'input_uri_value' + assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] + + +@pytest.mark.asyncio +async def test_annotate_video_flattened_error_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.annotate_video( + video_intelligence.AnnotateVideoRequest(), + input_uri='input_uri_value', + features=[video_intelligence.Feature.LABEL_DETECTION], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VideoIntelligenceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VideoIntelligenceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VideoIntelligenceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VideoIntelligenceServiceGrpcTransport, + ) + +def test_video_intelligence_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_video_intelligence_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VideoIntelligenceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'annotate_video', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_video_intelligence_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VideoIntelligenceServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VideoIntelligenceServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_video_intelligence_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VideoIntelligenceServiceGrpcTransport, + transports.VideoIntelligenceServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), + (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "videointelligence.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="videointelligence.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_video_intelligence_service_host_no_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:443' + + +def test_video_intelligence_service_host_with_port(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), + ) + assert client.transport._host == 'videointelligence.googleapis.com:8000' + +def test_video_intelligence_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_video_intelligence_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) +def test_video_intelligence_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_video_intelligence_service_grpc_lro_client(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_video_intelligence_service_grpc_lro_async_client(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = VideoIntelligenceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = VideoIntelligenceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VideoIntelligenceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = VideoIntelligenceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = VideoIntelligenceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = VideoIntelligenceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VideoIntelligenceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = VideoIntelligenceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VideoIntelligenceServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = VideoIntelligenceServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() From 66804bd8a4e04d2ba4318fcfc5c707e4544414b0 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 6 Oct 2021 22:56:21 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../async_client.py | 6 + .../video_intelligence_service/client.py | 18 +- .../transports/base.py | 9 + .../transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../types/video_intelligence.py | 27 + .../async_client.py | 6 + .../video_intelligence_service/client.py | 18 +- .../transports/base.py | 9 + .../transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../types/video_intelligence.py | 17 + .../async_client.py | 6 + .../video_intelligence_service/client.py | 18 +- .../transports/base.py | 9 + .../transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../types/video_intelligence.py | 15 + .../async_client.py | 6 + .../video_intelligence_service/client.py | 18 +- .../transports/base.py | 9 + .../transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../types/video_intelligence.py | 16 + .../async_client.py | 6 + .../client.py | 18 +- .../transports/base.py | 9 + .../transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../async_client.py | 6 + .../video_intelligence_service/client.py | 18 +- .../transports/base.py | 9 + .../transports/grpc.py | 3 + .../transports/grpc_asyncio.py | 3 + .../types/video_intelligence.py | 41 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 ---- owl-bot-staging/v1/docs/index.rst | 7 - .../v1/docs/videointelligence_v1/services.rst | 6 - .../v1/docs/videointelligence_v1/types.rst | 7 - .../video_intelligence_service.rst | 6 - .../cloud/videointelligence/__init__.py | 115 - .../google/cloud/videointelligence/py.typed | 2 - .../cloud/videointelligence_v1/__init__.py | 116 - .../videointelligence_v1/gapic_metadata.json | 33 - .../cloud/videointelligence_v1/py.typed | 2 - .../videointelligence_v1/services/__init__.py | 15 - .../video_intelligence_service/__init__.py | 22 - .../async_client.py | 274 --- .../video_intelligence_service/client.py | 455 ---- .../transports/__init__.py | 33 - .../transports/base.py | 191 -- .../transports/grpc.py | 277 --- .../transports/grpc_asyncio.py | 282 --- .../videointelligence_v1/types/__init__.py | 112 - .../types/video_intelligence.py | 1689 -------------- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 -- .../fixup_videointelligence_v1_keywords.py | 176 -- owl-bot-staging/v1/setup.py | 54 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/videointelligence_v1/__init__.py | 16 - .../test_video_intelligence_service.py | 1177 ---------- owl-bot-staging/v1beta2/.coveragerc | 17 - owl-bot-staging/v1beta2/MANIFEST.in | 2 - owl-bot-staging/v1beta2/README.rst | 49 - owl-bot-staging/v1beta2/docs/conf.py | 376 ---- owl-bot-staging/v1beta2/docs/index.rst | 7 - .../videointelligence_v1beta2/services.rst | 6 - .../docs/videointelligence_v1beta2/types.rst | 7 - .../video_intelligence_service.rst | 6 - .../cloud/videointelligence/__init__.py | 71 - .../google/cloud/videointelligence/py.typed | 2 - .../videointelligence_v1beta2/__init__.py | 72 - .../gapic_metadata.json | 33 - .../cloud/videointelligence_v1beta2/py.typed | 2 - .../services/__init__.py | 15 - .../video_intelligence_service/__init__.py | 22 - .../async_client.py | 274 --- .../video_intelligence_service/client.py | 455 ---- .../transports/__init__.py | 33 - .../transports/base.py | 191 -- .../transports/grpc.py | 277 --- .../transports/grpc_asyncio.py | 282 --- .../types/__init__.py | 68 - .../types/video_intelligence.py | 718 ------ owl-bot-staging/v1beta2/mypy.ini | 3 - owl-bot-staging/v1beta2/noxfile.py | 132 -- ...ixup_videointelligence_v1beta2_keywords.py | 176 -- owl-bot-staging/v1beta2/setup.py | 54 - owl-bot-staging/v1beta2/tests/__init__.py | 16 - .../v1beta2/tests/unit/__init__.py | 16 - .../v1beta2/tests/unit/gapic/__init__.py | 16 - .../videointelligence_v1beta2/__init__.py | 16 - .../test_video_intelligence_service.py | 1177 ---------- owl-bot-staging/v1p1beta1/.coveragerc | 17 - owl-bot-staging/v1p1beta1/MANIFEST.in | 2 - owl-bot-staging/v1p1beta1/README.rst | 49 - owl-bot-staging/v1p1beta1/docs/conf.py | 376 ---- owl-bot-staging/v1p1beta1/docs/index.rst | 7 - .../videointelligence_v1p1beta1/services.rst | 6 - .../videointelligence_v1p1beta1/types.rst | 7 - .../video_intelligence_service.rst | 6 - .../cloud/videointelligence/__init__.py | 71 - .../google/cloud/videointelligence/py.typed | 2 - .../videointelligence_v1p1beta1/__init__.py | 72 - .../gapic_metadata.json | 33 - .../videointelligence_v1p1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../video_intelligence_service/__init__.py | 22 - .../async_client.py | 274 --- .../video_intelligence_service/client.py | 455 ---- .../transports/__init__.py | 33 - .../transports/base.py | 191 -- .../transports/grpc.py | 277 --- .../transports/grpc_asyncio.py | 282 --- .../types/__init__.py | 68 - .../types/video_intelligence.py | 779 ------- owl-bot-staging/v1p1beta1/mypy.ini | 3 - owl-bot-staging/v1p1beta1/noxfile.py | 132 -- ...up_videointelligence_v1p1beta1_keywords.py | 176 -- owl-bot-staging/v1p1beta1/setup.py | 54 - owl-bot-staging/v1p1beta1/tests/__init__.py | 16 - .../v1p1beta1/tests/unit/__init__.py | 16 - .../v1p1beta1/tests/unit/gapic/__init__.py | 16 - .../videointelligence_v1p1beta1/__init__.py | 16 - .../test_video_intelligence_service.py | 1177 ---------- owl-bot-staging/v1p2beta1/.coveragerc | 17 - owl-bot-staging/v1p2beta1/MANIFEST.in | 2 - owl-bot-staging/v1p2beta1/README.rst | 49 - owl-bot-staging/v1p2beta1/docs/conf.py | 376 ---- owl-bot-staging/v1p2beta1/docs/index.rst | 7 - .../videointelligence_v1p2beta1/services.rst | 6 - .../videointelligence_v1p2beta1/types.rst | 7 - .../video_intelligence_service.rst | 6 - .../cloud/videointelligence/__init__.py | 79 - .../google/cloud/videointelligence/py.typed | 2 - .../videointelligence_v1p2beta1/__init__.py | 80 - .../gapic_metadata.json | 33 - .../videointelligence_v1p2beta1/py.typed | 2 - .../services/__init__.py | 15 - .../video_intelligence_service/__init__.py | 22 - .../async_client.py | 274 --- .../video_intelligence_service/client.py | 455 ---- .../transports/__init__.py | 33 - .../transports/base.py | 191 -- .../transports/grpc.py | 277 --- .../transports/grpc_asyncio.py | 282 --- .../types/__init__.py | 76 - .../types/video_intelligence.py | 853 ------- owl-bot-staging/v1p2beta1/mypy.ini | 3 - owl-bot-staging/v1p2beta1/noxfile.py | 132 -- ...up_videointelligence_v1p2beta1_keywords.py | 176 -- owl-bot-staging/v1p2beta1/setup.py | 54 - owl-bot-staging/v1p2beta1/tests/__init__.py | 16 - .../v1p2beta1/tests/unit/__init__.py | 16 - .../v1p2beta1/tests/unit/gapic/__init__.py | 16 - .../videointelligence_v1p2beta1/__init__.py | 16 - .../test_video_intelligence_service.py | 1177 ---------- owl-bot-staging/v1p3beta1/.coveragerc | 17 - owl-bot-staging/v1p3beta1/MANIFEST.in | 2 - owl-bot-staging/v1p3beta1/README.rst | 49 - owl-bot-staging/v1p3beta1/docs/conf.py | 376 ---- owl-bot-staging/v1p3beta1/docs/index.rst | 7 - .../videointelligence_v1p3beta1/services.rst | 7 - .../streaming_video_intelligence_service.rst | 6 - .../videointelligence_v1p3beta1/types.rst | 7 - .../video_intelligence_service.rst | 6 - .../cloud/videointelligence/__init__.py | 145 -- .../google/cloud/videointelligence/py.typed | 2 - .../videointelligence_v1p3beta1/__init__.py | 146 -- .../gapic_metadata.json | 57 - .../videointelligence_v1p3beta1/py.typed | 2 - .../services/__init__.py | 15 - .../__init__.py | 22 - .../async_client.py | 224 -- .../client.py | 401 ---- .../transports/__init__.py | 33 - .../transports/base.py | 184 -- .../transports/grpc.py | 257 --- .../transports/grpc_asyncio.py | 262 --- .../video_intelligence_service/__init__.py | 22 - .../async_client.py | 274 --- .../video_intelligence_service/client.py | 455 ---- .../transports/__init__.py | 33 - .../transports/base.py | 191 -- .../transports/grpc.py | 277 --- .../transports/grpc_asyncio.py | 282 --- .../types/__init__.py | 138 -- .../types/video_intelligence.py | 1998 ----------------- owl-bot-staging/v1p3beta1/mypy.ini | 3 - owl-bot-staging/v1p3beta1/noxfile.py | 132 -- ...up_videointelligence_v1p3beta1_keywords.py | 177 -- owl-bot-staging/v1p3beta1/setup.py | 54 - owl-bot-staging/v1p3beta1/tests/__init__.py | 16 - .../v1p3beta1/tests/unit/__init__.py | 16 - .../v1p3beta1/tests/unit/gapic/__init__.py | 16 - .../videointelligence_v1p3beta1/__init__.py | 16 - ...st_streaming_video_intelligence_service.py | 1031 --------- .../test_video_intelligence_service.py | 1177 ---------- .../test_video_intelligence_service.py | 50 + .../test_video_intelligence_service.py | 50 + .../test_video_intelligence_service.py | 50 + .../test_video_intelligence_service.py | 50 + ...st_streaming_video_intelligence_service.py | 50 + .../test_video_intelligence_service.py | 50 + 210 files changed, 623 insertions(+), 28249 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/videointelligence_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/videointelligence_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py delete mode 100644 owl-bot-staging/v1beta2/.coveragerc delete mode 100644 owl-bot-staging/v1beta2/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta2/README.rst delete mode 100644 owl-bot-staging/v1beta2/docs/conf.py delete mode 100644 owl-bot-staging/v1beta2/docs/index.rst delete mode 100644 owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst delete mode 100644 owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst delete mode 100644 owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py delete mode 100644 owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py delete mode 100644 owl-bot-staging/v1beta2/mypy.ini delete mode 100644 owl-bot-staging/v1beta2/noxfile.py delete mode 100644 owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py delete mode 100644 owl-bot-staging/v1beta2/setup.py delete mode 100644 owl-bot-staging/v1beta2/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py delete mode 100644 owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py delete mode 100644 owl-bot-staging/v1p1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p1beta1/README.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py delete mode 100644 owl-bot-staging/v1p1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py delete mode 100644 owl-bot-staging/v1p1beta1/setup.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py delete mode 100644 owl-bot-staging/v1p2beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p2beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p2beta1/README.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p2beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py delete mode 100644 owl-bot-staging/v1p2beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p2beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py delete mode 100644 owl-bot-staging/v1p2beta1/setup.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py delete mode 100644 owl-bot-staging/v1p3beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p3beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p3beta1/README.rst delete mode 100644 owl-bot-staging/v1p3beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p3beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst delete mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst delete mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst delete mode 100644 owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py delete mode 100644 owl-bot-staging/v1p3beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p3beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py delete mode 100644 owl-bot-staging/v1p3beta1/setup.py delete mode 100644 owl-bot-staging/v1p3beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py delete mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py delete mode 100644 owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py diff --git a/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py b/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py index 1e72bd8f..95c8c0b5 100644 --- a/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py +++ b/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py @@ -276,6 +276,12 @@ async def annotate_video( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py b/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py index 6261b9a5..71d92661 100644 --- a/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py +++ b/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py @@ -331,10 +331,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def annotate_video( @@ -438,6 +435,19 @@ def annotate_video( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py b/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py index 0138e4a0..9e1d41db 100644 --- a/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py +++ b/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py @@ -173,6 +173,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py b/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py index ab9f9c5c..aad743ff 100644 --- a/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py +++ b/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py @@ -272,5 +272,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcTransport",) diff --git a/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py b/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py index 18771166..45e866a1 100644 --- a/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py +++ b/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -279,5 +279,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + return self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/videointelligence_v1/types/video_intelligence.py b/google/cloud/videointelligence_v1/types/video_intelligence.py index 078f5f0c..d9070658 100644 --- a/google/cloud/videointelligence_v1/types/video_intelligence.py +++ b/google/cloud/videointelligence_v1/types/video_intelligence.py @@ -107,6 +107,7 @@ class Likelihood(proto.Enum): class AnnotateVideoRequest(proto.Message): r"""Video annotation request. + Attributes: input_uri (str): Input video location. Currently, only `Cloud @@ -157,6 +158,7 @@ class AnnotateVideoRequest(proto.Message): class VideoContext(proto.Message): r"""Video context and/or feature-specific parameters. + Attributes: segments (Sequence[google.cloud.videointelligence_v1.types.VideoSegment]): Video segments to annotate. The segments may @@ -210,6 +212,7 @@ class VideoContext(proto.Message): class LabelDetectionConfig(proto.Message): r"""Config for LABEL_DETECTION. + Attributes: label_detection_mode (google.cloud.videointelligence_v1.types.LabelDetectionMode): What labels should be detected with LABEL_DETECTION, in @@ -251,6 +254,7 @@ class LabelDetectionConfig(proto.Message): class ShotChangeDetectionConfig(proto.Message): r"""Config for SHOT_CHANGE_DETECTION. + Attributes: model (str): Model to use for shot change detection. @@ -263,6 +267,7 @@ class ShotChangeDetectionConfig(proto.Message): class ObjectTrackingConfig(proto.Message): r"""Config for OBJECT_TRACKING. + Attributes: model (str): Model to use for object tracking. @@ -275,6 +280,7 @@ class ObjectTrackingConfig(proto.Message): class FaceDetectionConfig(proto.Message): r"""Config for FACE_DETECTION. + Attributes: model (str): Model to use for face detection. @@ -296,6 +302,7 @@ class FaceDetectionConfig(proto.Message): class PersonDetectionConfig(proto.Message): r"""Config for PERSON_DETECTION. + Attributes: include_bounding_boxes (bool): Whether bounding boxes are included in the @@ -317,6 +324,7 @@ class PersonDetectionConfig(proto.Message): class ExplicitContentDetectionConfig(proto.Message): r"""Config for EXPLICIT_CONTENT_DETECTION. + Attributes: model (str): Model to use for explicit content detection. @@ -329,6 +337,7 @@ class ExplicitContentDetectionConfig(proto.Message): class TextDetectionConfig(proto.Message): r"""Config for TEXT_DETECTION. + Attributes: language_hints (Sequence[str]): Language hint can be specified if the @@ -351,6 +360,7 @@ class TextDetectionConfig(proto.Message): class VideoSegment(proto.Message): r"""Video segment. + Attributes: start_time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -372,6 +382,7 @@ class VideoSegment(proto.Message): class LabelSegment(proto.Message): r"""Video segment level annotation results for label detection. + Attributes: segment (google.cloud.videointelligence_v1.types.VideoSegment): Video segment where a label was detected. @@ -385,6 +396,7 @@ class LabelSegment(proto.Message): class LabelFrame(proto.Message): r"""Video frame level annotation results for label detection. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -400,6 +412,7 @@ class LabelFrame(proto.Message): class Entity(proto.Message): r"""Detected entity from video analysis. + Attributes: entity_id (str): Opaque entity ID. Some IDs may be available in `Google @@ -418,6 +431,7 @@ class Entity(proto.Message): class LabelAnnotation(proto.Message): r"""Label annotation. + Attributes: entity (google.cloud.videointelligence_v1.types.Entity): Detected entity. @@ -444,6 +458,7 @@ class LabelAnnotation(proto.Message): class ExplicitContentFrame(proto.Message): r"""Video frame level annotation results for explicit content. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -499,6 +514,7 @@ class NormalizedBoundingBox(proto.Message): class FaceDetectionAnnotation(proto.Message): r"""Face detection annotation. + Attributes: tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): The face tracks with attributes. @@ -515,6 +531,7 @@ class FaceDetectionAnnotation(proto.Message): class PersonDetectionAnnotation(proto.Message): r"""Person detection annotation per video. + Attributes: tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): The detected tracks of a person. @@ -528,6 +545,7 @@ class PersonDetectionAnnotation(proto.Message): class FaceSegment(proto.Message): r"""Video segment level annotation results for face detection. + Attributes: segment (google.cloud.videointelligence_v1.types.VideoSegment): Video segment where a face was detected. @@ -538,6 +556,7 @@ class FaceSegment(proto.Message): class FaceFrame(proto.Message): r"""Deprecated. No effect. + Attributes: normalized_bounding_boxes (Sequence[google.cloud.videointelligence_v1.types.NormalizedBoundingBox]): Normalized Bounding boxes in a frame. @@ -558,6 +577,7 @@ class FaceFrame(proto.Message): class FaceAnnotation(proto.Message): r"""Deprecated. No effect. + Attributes: thumbnail (bytes): Thumbnail of a representative face view (in @@ -606,6 +626,7 @@ class TimestampedObject(proto.Message): class Track(proto.Message): r"""A track of an object instance. + Attributes: segment (google.cloud.videointelligence_v1.types.VideoSegment): Video segment of a track. @@ -675,6 +696,7 @@ class DetectedLandmark(proto.Message): class VideoAnnotationResults(proto.Message): r"""Annotation results for a single video. + Attributes: input_uri (str): Video file location in `Cloud @@ -806,6 +828,7 @@ class AnnotateVideoResponse(proto.Message): class VideoAnnotationProgress(proto.Message): r"""Annotation progress for a single video. + Attributes: input_uri (str): Video file location in `Cloud @@ -851,6 +874,7 @@ class AnnotateVideoProgress(proto.Message): class SpeechTranscriptionConfig(proto.Message): r"""Config for SPEECH_TRANSCRIPTION. + Attributes: language_code (str): Required. *Required* The language of the supplied audio as a @@ -969,6 +993,7 @@ class SpeechTranscription(proto.Message): class SpeechRecognitionAlternative(proto.Message): r"""Alternative hypotheses (a.k.a. n-best list). + Attributes: transcript (str): Transcript text representing the words that @@ -1077,6 +1102,7 @@ class NormalizedBoundingPoly(proto.Message): class TextSegment(proto.Message): r"""Video segment level annotation results for text detection. + Attributes: segment (google.cloud.videointelligence_v1.types.VideoSegment): Video segment where a text snippet was @@ -1155,6 +1181,7 @@ class ObjectTrackingFrame(proto.Message): class ObjectTrackingAnnotation(proto.Message): r"""Annotations corresponding to one tracked object. + Attributes: segment (google.cloud.videointelligence_v1.types.VideoSegment): Non-streaming batch mode ONLY. diff --git a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py index dafe7b7c..7208a72d 100644 --- a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py +++ b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py @@ -276,6 +276,12 @@ async def annotate_video( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py index c4cfc802..49053746 100644 --- a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py +++ b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py @@ -331,10 +331,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def annotate_video( @@ -438,6 +435,19 @@ def annotate_video( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py index a49bd4fe..858cf016 100644 --- a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py +++ b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py @@ -173,6 +173,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py index 9ecf5e82..77b203d6 100644 --- a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py +++ b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py @@ -272,5 +272,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcTransport",) diff --git a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py index ddef810d..ca2b00d2 100644 --- a/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py +++ b/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py @@ -279,5 +279,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + return self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/videointelligence_v1beta2/types/video_intelligence.py b/google/cloud/videointelligence_v1beta2/types/video_intelligence.py index fb2d38e8..8b0ee23b 100644 --- a/google/cloud/videointelligence_v1beta2/types/video_intelligence.py +++ b/google/cloud/videointelligence_v1beta2/types/video_intelligence.py @@ -80,6 +80,7 @@ class Likelihood(proto.Enum): class AnnotateVideoRequest(proto.Message): r"""Video annotation request. + Attributes: input_uri (str): Input video location. Currently, only `Google Cloud @@ -131,6 +132,7 @@ class AnnotateVideoRequest(proto.Message): class VideoContext(proto.Message): r"""Video context and/or feature-specific parameters. + Attributes: segments (Sequence[google.cloud.videointelligence_v1beta2.types.VideoSegment]): Video segments to annotate. The segments may @@ -164,6 +166,7 @@ class VideoContext(proto.Message): class LabelDetectionConfig(proto.Message): r"""Config for LABEL_DETECTION. + Attributes: label_detection_mode (google.cloud.videointelligence_v1beta2.types.LabelDetectionMode): What labels should be detected with LABEL_DETECTION, in @@ -187,6 +190,7 @@ class LabelDetectionConfig(proto.Message): class ShotChangeDetectionConfig(proto.Message): r"""Config for SHOT_CHANGE_DETECTION. + Attributes: model (str): Model to use for shot change detection. @@ -199,6 +203,7 @@ class ShotChangeDetectionConfig(proto.Message): class ExplicitContentDetectionConfig(proto.Message): r"""Config for EXPLICIT_CONTENT_DETECTION. + Attributes: model (str): Model to use for explicit content detection. @@ -211,6 +216,7 @@ class ExplicitContentDetectionConfig(proto.Message): class FaceDetectionConfig(proto.Message): r"""Config for FACE_DETECTION. + Attributes: model (str): Model to use for face detection. @@ -227,6 +233,7 @@ class FaceDetectionConfig(proto.Message): class VideoSegment(proto.Message): r"""Video segment. + Attributes: start_time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -248,6 +255,7 @@ class VideoSegment(proto.Message): class LabelSegment(proto.Message): r"""Video segment level annotation results for label detection. + Attributes: segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): Video segment where a label was detected. @@ -261,6 +269,7 @@ class LabelSegment(proto.Message): class LabelFrame(proto.Message): r"""Video frame level annotation results for label detection. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -276,6 +285,7 @@ class LabelFrame(proto.Message): class Entity(proto.Message): r"""Detected entity from video analysis. + Attributes: entity_id (str): Opaque entity ID. Some IDs may be available in `Google @@ -294,6 +304,7 @@ class Entity(proto.Message): class LabelAnnotation(proto.Message): r"""Label annotation. + Attributes: entity (google.cloud.videointelligence_v1beta2.types.Entity): Detected entity. @@ -317,6 +328,7 @@ class LabelAnnotation(proto.Message): class ExplicitContentFrame(proto.Message): r"""Video frame level annotation results for explicit content. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -369,6 +381,7 @@ class NormalizedBoundingBox(proto.Message): class FaceSegment(proto.Message): r"""Video segment level annotation results for face detection. + Attributes: segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): Video segment where a face was detected. @@ -379,6 +392,7 @@ class FaceSegment(proto.Message): class FaceFrame(proto.Message): r"""Video frame level annotation results for face detection. + Attributes: normalized_bounding_boxes (Sequence[google.cloud.videointelligence_v1beta2.types.NormalizedBoundingBox]): Normalized Bounding boxes in a frame. @@ -399,6 +413,7 @@ class FaceFrame(proto.Message): class FaceAnnotation(proto.Message): r"""Face annotation. + Attributes: thumbnail (bytes): Thumbnail of a representative face view (in @@ -416,6 +431,7 @@ class FaceAnnotation(proto.Message): class VideoAnnotationResults(proto.Message): r"""Annotation results for a single video. + Attributes: input_uri (str): Video file location in `Google Cloud @@ -486,6 +502,7 @@ class AnnotateVideoResponse(proto.Message): class VideoAnnotationProgress(proto.Message): r"""Annotation progress for a single video. + Attributes: input_uri (str): Video file location in `Google Cloud diff --git a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py index 5f3d922e..d67e7b6b 100644 --- a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py +++ b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py @@ -276,6 +276,12 @@ async def annotate_video( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py index 726abf60..cfd996f5 100644 --- a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py +++ b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py @@ -331,10 +331,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def annotate_video( @@ -438,6 +435,19 @@ def annotate_video( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py index e817294f..d15b43c1 100644 --- a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py +++ b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py @@ -173,6 +173,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py index d94be04b..fe7b4e6d 100644 --- a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py +++ b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py @@ -272,5 +272,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcTransport",) diff --git a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py index f039e75f..0ebeb48e 100644 --- a/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py +++ b/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -279,5 +279,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + return self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py b/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py index 7c529fdf..0fbbbc93 100644 --- a/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py +++ b/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py @@ -80,6 +80,7 @@ class Likelihood(proto.Enum): class AnnotateVideoRequest(proto.Message): r"""Video annotation request. + Attributes: input_uri (str): Input video location. Currently, only `Google Cloud @@ -131,6 +132,7 @@ class AnnotateVideoRequest(proto.Message): class VideoContext(proto.Message): r"""Video context and/or feature-specific parameters. + Attributes: segments (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoSegment]): Video segments to annotate. The segments may @@ -164,6 +166,7 @@ class VideoContext(proto.Message): class LabelDetectionConfig(proto.Message): r"""Config for LABEL_DETECTION. + Attributes: label_detection_mode (google.cloud.videointelligence_v1p1beta1.types.LabelDetectionMode): What labels should be detected with LABEL_DETECTION, in @@ -187,6 +190,7 @@ class LabelDetectionConfig(proto.Message): class ShotChangeDetectionConfig(proto.Message): r"""Config for SHOT_CHANGE_DETECTION. + Attributes: model (str): Model to use for shot change detection. @@ -199,6 +203,7 @@ class ShotChangeDetectionConfig(proto.Message): class ExplicitContentDetectionConfig(proto.Message): r"""Config for EXPLICIT_CONTENT_DETECTION. + Attributes: model (str): Model to use for explicit content detection. @@ -211,6 +216,7 @@ class ExplicitContentDetectionConfig(proto.Message): class VideoSegment(proto.Message): r"""Video segment. + Attributes: start_time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -232,6 +238,7 @@ class VideoSegment(proto.Message): class LabelSegment(proto.Message): r"""Video segment level annotation results for label detection. + Attributes: segment (google.cloud.videointelligence_v1p1beta1.types.VideoSegment): Video segment where a label was detected. @@ -245,6 +252,7 @@ class LabelSegment(proto.Message): class LabelFrame(proto.Message): r"""Video frame level annotation results for label detection. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -260,6 +268,7 @@ class LabelFrame(proto.Message): class Entity(proto.Message): r"""Detected entity from video analysis. + Attributes: entity_id (str): Opaque entity ID. Some IDs may be available in `Google @@ -278,6 +287,7 @@ class Entity(proto.Message): class LabelAnnotation(proto.Message): r"""Label annotation. + Attributes: entity (google.cloud.videointelligence_v1p1beta1.types.Entity): Detected entity. @@ -301,6 +311,7 @@ class LabelAnnotation(proto.Message): class ExplicitContentFrame(proto.Message): r"""Video frame level annotation results for explicit content. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -332,6 +343,7 @@ class ExplicitContentAnnotation(proto.Message): class VideoAnnotationResults(proto.Message): r"""Annotation results for a single video. + Attributes: input_uri (str): Output only. Video file location in `Google Cloud @@ -401,6 +413,7 @@ class AnnotateVideoResponse(proto.Message): class VideoAnnotationProgress(proto.Message): r"""Annotation progress for a single video. + Attributes: input_uri (str): Output only. Video file location in `Google Cloud @@ -440,6 +453,7 @@ class AnnotateVideoProgress(proto.Message): class SpeechTranscriptionConfig(proto.Message): r"""Config for SPEECH_TRANSCRIPTION. + Attributes: language_code (str): Required. *Required* The language of the supplied audio as a @@ -530,6 +544,7 @@ class SpeechTranscription(proto.Message): class SpeechRecognitionAlternative(proto.Message): r"""Alternative hypotheses (a.k.a. n-best list). + Attributes: transcript (str): Output only. Transcript text representing the diff --git a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py index f3af55da..534fe915 100644 --- a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py +++ b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py @@ -276,6 +276,12 @@ async def annotate_video( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py index 9fce56e7..f35a1aea 100644 --- a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py +++ b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py @@ -331,10 +331,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def annotate_video( @@ -438,6 +435,19 @@ def annotate_video( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py index 486e90ba..42e62bde 100644 --- a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py +++ b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py @@ -173,6 +173,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py index 0e1f0166..e22650e6 100644 --- a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py +++ b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py @@ -272,5 +272,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcTransport",) diff --git a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py index 61775ef4..71a69687 100644 --- a/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py +++ b/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -279,5 +279,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + return self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py b/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py index 754ad23a..eca3b5a9 100644 --- a/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py +++ b/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py @@ -85,6 +85,7 @@ class Likelihood(proto.Enum): class AnnotateVideoRequest(proto.Message): r"""Video annotation request. + Attributes: input_uri (str): Input video location. Currently, only `Google Cloud @@ -136,6 +137,7 @@ class AnnotateVideoRequest(proto.Message): class VideoContext(proto.Message): r"""Video context and/or feature-specific parameters. + Attributes: segments (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoSegment]): Video segments to annotate. The segments may @@ -169,6 +171,7 @@ class VideoContext(proto.Message): class LabelDetectionConfig(proto.Message): r"""Config for LABEL_DETECTION. + Attributes: label_detection_mode (google.cloud.videointelligence_v1p2beta1.types.LabelDetectionMode): What labels should be detected with LABEL_DETECTION, in @@ -192,6 +195,7 @@ class LabelDetectionConfig(proto.Message): class ShotChangeDetectionConfig(proto.Message): r"""Config for SHOT_CHANGE_DETECTION. + Attributes: model (str): Model to use for shot change detection. @@ -204,6 +208,7 @@ class ShotChangeDetectionConfig(proto.Message): class ExplicitContentDetectionConfig(proto.Message): r"""Config for EXPLICIT_CONTENT_DETECTION. + Attributes: model (str): Model to use for explicit content detection. @@ -216,6 +221,7 @@ class ExplicitContentDetectionConfig(proto.Message): class TextDetectionConfig(proto.Message): r"""Config for TEXT_DETECTION. + Attributes: language_hints (Sequence[str]): Language hint can be specified if the @@ -233,6 +239,7 @@ class TextDetectionConfig(proto.Message): class VideoSegment(proto.Message): r"""Video segment. + Attributes: start_time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -254,6 +261,7 @@ class VideoSegment(proto.Message): class LabelSegment(proto.Message): r"""Video segment level annotation results for label detection. + Attributes: segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): Video segment where a label was detected. @@ -267,6 +275,7 @@ class LabelSegment(proto.Message): class LabelFrame(proto.Message): r"""Video frame level annotation results for label detection. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -282,6 +291,7 @@ class LabelFrame(proto.Message): class Entity(proto.Message): r"""Detected entity from video analysis. + Attributes: entity_id (str): Opaque entity ID. Some IDs may be available in `Google @@ -300,6 +310,7 @@ class Entity(proto.Message): class LabelAnnotation(proto.Message): r"""Label annotation. + Attributes: entity (google.cloud.videointelligence_v1p2beta1.types.Entity): Detected entity. @@ -323,6 +334,7 @@ class LabelAnnotation(proto.Message): class ExplicitContentFrame(proto.Message): r"""Video frame level annotation results for explicit content. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -375,6 +387,7 @@ class NormalizedBoundingBox(proto.Message): class VideoAnnotationResults(proto.Message): r"""Annotation results for a single video. + Attributes: input_uri (str): Video file location in `Google Cloud @@ -453,6 +466,7 @@ class AnnotateVideoResponse(proto.Message): class VideoAnnotationProgress(proto.Message): r"""Annotation progress for a single video. + Attributes: input_uri (str): Video file location in `Google Cloud @@ -528,6 +542,7 @@ class NormalizedBoundingPoly(proto.Message): class TextSegment(proto.Message): r"""Video segment level annotation results for text detection. + Attributes: segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): Video segment where a text snippet was @@ -603,6 +618,7 @@ class ObjectTrackingFrame(proto.Message): class ObjectTrackingAnnotation(proto.Message): r"""Annotations corresponding to one tracked object. + Attributes: entity (google.cloud.videointelligence_v1p2beta1.types.Entity): Entity to specify the object category that diff --git a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py index 5b86c803..d4af4ad9 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py +++ b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py @@ -246,6 +246,12 @@ def streaming_annotate_video( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py index 430b8a91..ce9de815 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py +++ b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py @@ -339,10 +339,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def streaming_annotate_video( @@ -391,6 +388,19 @@ def streaming_annotate_video( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py index a7693b16..f9f28552 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py +++ b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py @@ -171,6 +171,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def streaming_annotate_video( self, diff --git a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py index 2380e158..238b8051 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py +++ b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py @@ -259,5 +259,8 @@ def streaming_annotate_video( ) return self._stubs["streaming_annotate_video"] + def close(self): + self.grpc_channel.close() + __all__ = ("StreamingVideoIntelligenceServiceGrpcTransport",) diff --git a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py index 4de007f2..7978ef1e 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py +++ b/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py @@ -262,5 +262,8 @@ def streaming_annotate_video( ) return self._stubs["streaming_annotate_video"] + def close(self): + return self.grpc_channel.close() + __all__ = ("StreamingVideoIntelligenceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py index b9481b55..ed69072a 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py +++ b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py @@ -276,6 +276,12 @@ async def annotate_video( # Done; return the response. return response + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py index cae9d972..6ad5c32a 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py +++ b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py @@ -331,10 +331,7 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), + always_use_jwt_access=True, ) def annotate_video( @@ -438,6 +435,19 @@ def annotate_video( # Done; return the response. return response + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py index 64fa95a0..6b8e4121 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py +++ b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py @@ -173,6 +173,15 @@ def _prep_wrapped_messages(self, client_info): ), } + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py index 5b686dda..5f075362 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py +++ b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py @@ -272,5 +272,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcTransport",) diff --git a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py index 8f0c5638..54f3ebc7 100644 --- a/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py +++ b/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py @@ -279,5 +279,8 @@ def annotate_video( ) return self._stubs["annotate_video"] + def close(self): + return self.grpc_channel.close() + __all__ = ("VideoIntelligenceServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py b/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py index fb3374ee..38e72d63 100644 --- a/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py +++ b/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py @@ -133,6 +133,7 @@ class Feature(proto.Enum): class AnnotateVideoRequest(proto.Message): r"""Video annotation request. + Attributes: input_uri (str): Input video location. Currently, only `Cloud @@ -183,6 +184,7 @@ class AnnotateVideoRequest(proto.Message): class VideoContext(proto.Message): r"""Video context and/or feature-specific parameters. + Attributes: segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): Video segments to annotate. The segments may @@ -236,6 +238,7 @@ class VideoContext(proto.Message): class LabelDetectionConfig(proto.Message): r"""Config for LABEL_DETECTION. + Attributes: label_detection_mode (google.cloud.videointelligence_v1p3beta1.types.LabelDetectionMode): What labels should be detected with LABEL_DETECTION, in @@ -277,6 +280,7 @@ class LabelDetectionConfig(proto.Message): class ShotChangeDetectionConfig(proto.Message): r"""Config for SHOT_CHANGE_DETECTION. + Attributes: model (str): Model to use for shot change detection. @@ -289,6 +293,7 @@ class ShotChangeDetectionConfig(proto.Message): class ObjectTrackingConfig(proto.Message): r"""Config for OBJECT_TRACKING. + Attributes: model (str): Model to use for object tracking. @@ -301,6 +306,7 @@ class ObjectTrackingConfig(proto.Message): class ExplicitContentDetectionConfig(proto.Message): r"""Config for EXPLICIT_CONTENT_DETECTION. + Attributes: model (str): Model to use for explicit content detection. @@ -313,6 +319,7 @@ class ExplicitContentDetectionConfig(proto.Message): class FaceDetectionConfig(proto.Message): r"""Config for FACE_DETECTION. + Attributes: model (str): Model to use for face detection. @@ -334,6 +341,7 @@ class FaceDetectionConfig(proto.Message): class PersonDetectionConfig(proto.Message): r"""Config for PERSON_DETECTION. + Attributes: include_bounding_boxes (bool): Whether bounding boxes are included in the @@ -355,6 +363,7 @@ class PersonDetectionConfig(proto.Message): class TextDetectionConfig(proto.Message): r"""Config for TEXT_DETECTION. + Attributes: language_hints (Sequence[str]): Language hint can be specified if the @@ -377,6 +386,7 @@ class TextDetectionConfig(proto.Message): class VideoSegment(proto.Message): r"""Video segment. + Attributes: start_time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -398,6 +408,7 @@ class VideoSegment(proto.Message): class LabelSegment(proto.Message): r"""Video segment level annotation results for label detection. + Attributes: segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): Video segment where a label was detected. @@ -411,6 +422,7 @@ class LabelSegment(proto.Message): class LabelFrame(proto.Message): r"""Video frame level annotation results for label detection. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -426,6 +438,7 @@ class LabelFrame(proto.Message): class Entity(proto.Message): r"""Detected entity from video analysis. + Attributes: entity_id (str): Opaque entity ID. Some IDs may be available in `Google @@ -444,6 +457,7 @@ class Entity(proto.Message): class LabelAnnotation(proto.Message): r"""Label annotation. + Attributes: entity (google.cloud.videointelligence_v1p3beta1.types.Entity): Detected entity. @@ -467,6 +481,7 @@ class LabelAnnotation(proto.Message): class ExplicitContentFrame(proto.Message): r"""Video frame level annotation results for explicit content. + Attributes: time_offset (google.protobuf.duration_pb2.Duration): Time-offset, relative to the beginning of the @@ -550,6 +565,7 @@ class TimestampedObject(proto.Message): class Track(proto.Message): r"""A track of an object instance. + Attributes: segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): Video segment of a track. @@ -597,6 +613,7 @@ class DetectedAttribute(proto.Message): class Celebrity(proto.Message): r"""Celebrity definition. + Attributes: name (str): The resource name of the celebrity. Have the format @@ -630,6 +647,7 @@ class CelebrityTrack(proto.Message): class RecognizedCelebrity(proto.Message): r"""The recognized celebrity with confidence score. + Attributes: celebrity (google.cloud.videointelligence_v1p3beta1.types.Celebrity): The recognized celebrity. @@ -648,6 +666,7 @@ class RecognizedCelebrity(proto.Message): class CelebrityRecognitionAnnotation(proto.Message): r"""Celebrity recognition annotation per video. + Attributes: celebrity_tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.CelebrityTrack]): The tracks detected from the input video, @@ -684,6 +703,7 @@ class DetectedLandmark(proto.Message): class FaceDetectionAnnotation(proto.Message): r"""Face detection annotation. + Attributes: tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): The face tracks with attributes. @@ -697,6 +717,7 @@ class FaceDetectionAnnotation(proto.Message): class PersonDetectionAnnotation(proto.Message): r"""Person detection annotation per video. + Attributes: tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): The detected tracks of a person. @@ -707,6 +728,7 @@ class PersonDetectionAnnotation(proto.Message): class VideoAnnotationResults(proto.Message): r"""Annotation results for a single video. + Attributes: input_uri (str): Video file location in `Cloud @@ -837,6 +859,7 @@ class AnnotateVideoResponse(proto.Message): class VideoAnnotationProgress(proto.Message): r"""Annotation progress for a single video. + Attributes: input_uri (str): Video file location in `Cloud @@ -882,6 +905,7 @@ class AnnotateVideoProgress(proto.Message): class SpeechTranscriptionConfig(proto.Message): r"""Config for SPEECH_TRANSCRIPTION. + Attributes: language_code (str): Required. *Required* The language of the supplied audio as a @@ -1000,6 +1024,7 @@ class SpeechTranscription(proto.Message): class SpeechRecognitionAlternative(proto.Message): r"""Alternative hypotheses (a.k.a. n-best list). + Attributes: transcript (str): Transcript text representing the words that @@ -1108,6 +1133,7 @@ class NormalizedBoundingPoly(proto.Message): class TextSegment(proto.Message): r"""Video segment level annotation results for text detection. + Attributes: segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): Video segment where a text snippet was @@ -1183,6 +1209,7 @@ class ObjectTrackingFrame(proto.Message): class ObjectTrackingAnnotation(proto.Message): r"""Annotations corresponding to one tracked object. + Attributes: segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): Non-streaming batch mode ONLY. @@ -1410,11 +1437,13 @@ class StreamingVideoAnnotationResults(proto.Message): class StreamingShotChangeDetectionConfig(proto.Message): - r"""Config for STREAMING_SHOT_CHANGE_DETECTION. """ + r"""Config for STREAMING_SHOT_CHANGE_DETECTION. + """ class StreamingLabelDetectionConfig(proto.Message): r"""Config for STREAMING_LABEL_DETECTION. + Attributes: stationary_camera (bool): Whether the video has been captured from a @@ -1427,15 +1456,18 @@ class StreamingLabelDetectionConfig(proto.Message): class StreamingExplicitContentDetectionConfig(proto.Message): - r"""Config for STREAMING_EXPLICIT_CONTENT_DETECTION. """ + r"""Config for STREAMING_EXPLICIT_CONTENT_DETECTION. + """ class StreamingObjectTrackingConfig(proto.Message): - r"""Config for STREAMING_OBJECT_TRACKING. """ + r"""Config for STREAMING_OBJECT_TRACKING. + """ class StreamingAutomlActionRecognitionConfig(proto.Message): r"""Config for STREAMING_AUTOML_ACTION_RECOGNITION. + Attributes: model_name (str): Resource name of AutoML model. Format: @@ -1447,6 +1479,7 @@ class StreamingAutomlActionRecognitionConfig(proto.Message): class StreamingAutomlClassificationConfig(proto.Message): r"""Config for STREAMING_AUTOML_CLASSIFICATION. + Attributes: model_name (str): Resource name of AutoML model. Format: @@ -1458,6 +1491,7 @@ class StreamingAutomlClassificationConfig(proto.Message): class StreamingAutomlObjectTrackingConfig(proto.Message): r"""Config for STREAMING_AUTOML_OBJECT_TRACKING. + Attributes: model_name (str): Resource name of AutoML model. Format: @@ -1469,6 +1503,7 @@ class StreamingAutomlObjectTrackingConfig(proto.Message): class StreamingStorageConfig(proto.Message): r"""Config for streaming storage option. + Attributes: enable_storage_annotation_result (bool): Enable streaming storage. Default: false. diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 45c608f8..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/videointelligence/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 7e4e1e18..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/videointelligence *.py -recursive-include google/cloud/videointelligence_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index bedc3680..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Videointelligence API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Videointelligence API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 7a82f64b..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-videointelligence documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-videointelligence" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-videointelligence-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-videointelligence.tex", - u"google-cloud-videointelligence Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-videointelligence", - u"Google Cloud Videointelligence Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-videointelligence", - u"google-cloud-videointelligence Documentation", - author, - "google-cloud-videointelligence", - "GAPIC library for Google Cloud Videointelligence API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index edb2525a..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - videointelligence_v1/services - videointelligence_v1/types diff --git a/owl-bot-staging/v1/docs/videointelligence_v1/services.rst b/owl-bot-staging/v1/docs/videointelligence_v1/services.rst deleted file mode 100644 index ed2a27c6..00000000 --- a/owl-bot-staging/v1/docs/videointelligence_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Videointelligence v1 API -================================================== -.. toctree:: - :maxdepth: 2 - - video_intelligence_service diff --git a/owl-bot-staging/v1/docs/videointelligence_v1/types.rst b/owl-bot-staging/v1/docs/videointelligence_v1/types.rst deleted file mode 100644 index 6bada002..00000000 --- a/owl-bot-staging/v1/docs/videointelligence_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Videointelligence v1 API -=============================================== - -.. automodule:: google.cloud.videointelligence_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst b/owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst deleted file mode 100644 index d8d38ca3..00000000 --- a/owl-bot-staging/v1/docs/videointelligence_v1/video_intelligence_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -VideoIntelligenceService ------------------------------------------- - -.. automodule:: google.cloud.videointelligence_v1.services.video_intelligence_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence/__init__.py deleted file mode 100644 index b3b8fdb7..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence/__init__.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.videointelligence_v1.services.video_intelligence_service.client import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient - -from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoProgress -from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoRequest -from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoResponse -from google.cloud.videointelligence_v1.types.video_intelligence import DetectedAttribute -from google.cloud.videointelligence_v1.types.video_intelligence import DetectedLandmark -from google.cloud.videointelligence_v1.types.video_intelligence import Entity -from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentDetectionConfig -from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentFrame -from google.cloud.videointelligence_v1.types.video_intelligence import FaceAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionConfig -from google.cloud.videointelligence_v1.types.video_intelligence import FaceFrame -from google.cloud.videointelligence_v1.types.video_intelligence import FaceSegment -from google.cloud.videointelligence_v1.types.video_intelligence import LabelAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionConfig -from google.cloud.videointelligence_v1.types.video_intelligence import LabelFrame -from google.cloud.videointelligence_v1.types.video_intelligence import LabelSegment -from google.cloud.videointelligence_v1.types.video_intelligence import LogoRecognitionAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingBox -from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingPoly -from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedVertex -from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingConfig -from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingFrame -from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionConfig -from google.cloud.videointelligence_v1.types.video_intelligence import ShotChangeDetectionConfig -from google.cloud.videointelligence_v1.types.video_intelligence import SpeechContext -from google.cloud.videointelligence_v1.types.video_intelligence import SpeechRecognitionAlternative -from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscription -from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscriptionConfig -from google.cloud.videointelligence_v1.types.video_intelligence import TextAnnotation -from google.cloud.videointelligence_v1.types.video_intelligence import TextDetectionConfig -from google.cloud.videointelligence_v1.types.video_intelligence import TextFrame -from google.cloud.videointelligence_v1.types.video_intelligence import TextSegment -from google.cloud.videointelligence_v1.types.video_intelligence import TimestampedObject -from google.cloud.videointelligence_v1.types.video_intelligence import Track -from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationProgress -from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationResults -from google.cloud.videointelligence_v1.types.video_intelligence import VideoContext -from google.cloud.videointelligence_v1.types.video_intelligence import VideoSegment -from google.cloud.videointelligence_v1.types.video_intelligence import WordInfo -from google.cloud.videointelligence_v1.types.video_intelligence import Feature -from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionMode -from google.cloud.videointelligence_v1.types.video_intelligence import Likelihood - -__all__ = ('VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'DetectedAttribute', - 'DetectedLandmark', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'FaceAnnotation', - 'FaceDetectionAnnotation', - 'FaceDetectionConfig', - 'FaceFrame', - 'FaceSegment', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'LogoRecognitionAnnotation', - 'NormalizedBoundingBox', - 'NormalizedBoundingPoly', - 'NormalizedVertex', - 'ObjectTrackingAnnotation', - 'ObjectTrackingConfig', - 'ObjectTrackingFrame', - 'PersonDetectionAnnotation', - 'PersonDetectionConfig', - 'ShotChangeDetectionConfig', - 'SpeechContext', - 'SpeechRecognitionAlternative', - 'SpeechTranscription', - 'SpeechTranscriptionConfig', - 'TextAnnotation', - 'TextDetectionConfig', - 'TextFrame', - 'TextSegment', - 'TimestampedObject', - 'Track', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'WordInfo', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1/google/cloud/videointelligence/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py deleted file mode 100644 index 24afe1d1..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.video_intelligence_service import VideoIntelligenceServiceClient -from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient - -from .types.video_intelligence import AnnotateVideoProgress -from .types.video_intelligence import AnnotateVideoRequest -from .types.video_intelligence import AnnotateVideoResponse -from .types.video_intelligence import DetectedAttribute -from .types.video_intelligence import DetectedLandmark -from .types.video_intelligence import Entity -from .types.video_intelligence import ExplicitContentAnnotation -from .types.video_intelligence import ExplicitContentDetectionConfig -from .types.video_intelligence import ExplicitContentFrame -from .types.video_intelligence import FaceAnnotation -from .types.video_intelligence import FaceDetectionAnnotation -from .types.video_intelligence import FaceDetectionConfig -from .types.video_intelligence import FaceFrame -from .types.video_intelligence import FaceSegment -from .types.video_intelligence import LabelAnnotation -from .types.video_intelligence import LabelDetectionConfig -from .types.video_intelligence import LabelFrame -from .types.video_intelligence import LabelSegment -from .types.video_intelligence import LogoRecognitionAnnotation -from .types.video_intelligence import NormalizedBoundingBox -from .types.video_intelligence import NormalizedBoundingPoly -from .types.video_intelligence import NormalizedVertex -from .types.video_intelligence import ObjectTrackingAnnotation -from .types.video_intelligence import ObjectTrackingConfig -from .types.video_intelligence import ObjectTrackingFrame -from .types.video_intelligence import PersonDetectionAnnotation -from .types.video_intelligence import PersonDetectionConfig -from .types.video_intelligence import ShotChangeDetectionConfig -from .types.video_intelligence import SpeechContext -from .types.video_intelligence import SpeechRecognitionAlternative -from .types.video_intelligence import SpeechTranscription -from .types.video_intelligence import SpeechTranscriptionConfig -from .types.video_intelligence import TextAnnotation -from .types.video_intelligence import TextDetectionConfig -from .types.video_intelligence import TextFrame -from .types.video_intelligence import TextSegment -from .types.video_intelligence import TimestampedObject -from .types.video_intelligence import Track -from .types.video_intelligence import VideoAnnotationProgress -from .types.video_intelligence import VideoAnnotationResults -from .types.video_intelligence import VideoContext -from .types.video_intelligence import VideoSegment -from .types.video_intelligence import WordInfo -from .types.video_intelligence import Feature -from .types.video_intelligence import LabelDetectionMode -from .types.video_intelligence import Likelihood - -__all__ = ( - 'VideoIntelligenceServiceAsyncClient', -'AnnotateVideoProgress', -'AnnotateVideoRequest', -'AnnotateVideoResponse', -'DetectedAttribute', -'DetectedLandmark', -'Entity', -'ExplicitContentAnnotation', -'ExplicitContentDetectionConfig', -'ExplicitContentFrame', -'FaceAnnotation', -'FaceDetectionAnnotation', -'FaceDetectionConfig', -'FaceFrame', -'FaceSegment', -'Feature', -'LabelAnnotation', -'LabelDetectionConfig', -'LabelDetectionMode', -'LabelFrame', -'LabelSegment', -'Likelihood', -'LogoRecognitionAnnotation', -'NormalizedBoundingBox', -'NormalizedBoundingPoly', -'NormalizedVertex', -'ObjectTrackingAnnotation', -'ObjectTrackingConfig', -'ObjectTrackingFrame', -'PersonDetectionAnnotation', -'PersonDetectionConfig', -'ShotChangeDetectionConfig', -'SpeechContext', -'SpeechRecognitionAlternative', -'SpeechTranscription', -'SpeechTranscriptionConfig', -'TextAnnotation', -'TextDetectionConfig', -'TextFrame', -'TextSegment', -'TimestampedObject', -'Track', -'VideoAnnotationProgress', -'VideoAnnotationResults', -'VideoContext', -'VideoIntelligenceServiceClient', -'VideoSegment', -'WordInfo', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json deleted file mode 100644 index 016f216f..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/gapic_metadata.json +++ /dev/null @@ -1,33 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.videointelligence_v1", - "protoPackage": "google.cloud.videointelligence.v1", - "schema": "1.0", - "services": { - "VideoIntelligenceService": { - "clients": { - "grpc": { - "libraryClient": "VideoIntelligenceServiceClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VideoIntelligenceServiceAsyncClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed b/owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py deleted file mode 100644 index 4094cd26..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import VideoIntelligenceServiceClient -from .async_client import VideoIntelligenceServiceAsyncClient - -__all__ = ( - 'VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py deleted file mode 100644 index 671f6800..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/async_client.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport -from .client import VideoIntelligenceServiceClient - - -class VideoIntelligenceServiceAsyncClient: - """Service that implements the Video Intelligence API.""" - - _client: VideoIntelligenceServiceClient - - DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) - common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) - parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) - common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) - parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = VideoIntelligenceServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def annotate_video(self, - request: video_intelligence.AnnotateVideoRequest = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (:class:`google.cloud.videointelligence_v1.types.AnnotateVideoRequest`): - The request object. Video annotation request. - input_uri (:class:`str`): - Input video location. Currently, only `Cloud - Storage `__ URIs are - supported. URIs must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - To identify multiple videos, a video URI may include - wildcards in the ``object-id``. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - must be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (:class:`Sequence[google.cloud.videointelligence_v1.types.Feature]`): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = video_intelligence.AnnotateVideoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features: - request.features.extend(features) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py deleted file mode 100644 index 88cb9ef0..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/client.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VideoIntelligenceServiceGrpcTransport -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -class VideoIntelligenceServiceClientMeta(type): - """Metaclass for the VideoIntelligenceService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] - _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport - _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[VideoIntelligenceServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): - """Service that implements the Video Intelligence API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "videointelligence.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VideoIntelligenceServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, VideoIntelligenceServiceTransport): - # transport is a VideoIntelligenceServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def annotate_video(self, - request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (Union[google.cloud.videointelligence_v1.types.AnnotateVideoRequest, dict]): - The request object. Video annotation request. - input_uri (str): - Input video location. Currently, only `Cloud - Storage `__ URIs are - supported. URIs must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - To identify multiple videos, a video URI may include - wildcards in the ``object-id``. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - must be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (Sequence[google.cloud.videointelligence_v1.types.Feature]): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a video_intelligence.AnnotateVideoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, video_intelligence.AnnotateVideoRequest): - request = video_intelligence.AnnotateVideoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features is not None: - request.features = features - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.annotate_video] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py deleted file mode 100644 index ef66f264..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import VideoIntelligenceServiceTransport -from .grpc import VideoIntelligenceServiceGrpcTransport -from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] -_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport - -__all__ = ( - 'VideoIntelligenceServiceTransport', - 'VideoIntelligenceServiceGrpcTransport', - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py deleted file mode 100644 index efdf98ee..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/base.py +++ /dev/null @@ -1,191 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-videointelligence', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class VideoIntelligenceServiceTransport(abc.ABC): - """Abstract transport class for VideoIntelligenceService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'videointelligence.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.annotate_video: gapic_v1.method.wrap_method( - self.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VideoIntelligenceServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py deleted file mode 100644 index ecef4959..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.videointelligence_v1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO - - -class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): - """gRPC backend transport for VideoIntelligenceService. - - Service that implements the Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - operations_pb2.Operation]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'VideoIntelligenceServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py deleted file mode 100644 index cdc09adc..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/services/video_intelligence_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.videointelligence_v1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import VideoIntelligenceServiceGrpcTransport - - -class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): - """gRPC AsyncIO backend transport for VideoIntelligenceService. - - Service that implements the Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py deleted file mode 100644 index 597262b1..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/__init__.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .video_intelligence import ( - AnnotateVideoProgress, - AnnotateVideoRequest, - AnnotateVideoResponse, - DetectedAttribute, - DetectedLandmark, - Entity, - ExplicitContentAnnotation, - ExplicitContentDetectionConfig, - ExplicitContentFrame, - FaceAnnotation, - FaceDetectionAnnotation, - FaceDetectionConfig, - FaceFrame, - FaceSegment, - LabelAnnotation, - LabelDetectionConfig, - LabelFrame, - LabelSegment, - LogoRecognitionAnnotation, - NormalizedBoundingBox, - NormalizedBoundingPoly, - NormalizedVertex, - ObjectTrackingAnnotation, - ObjectTrackingConfig, - ObjectTrackingFrame, - PersonDetectionAnnotation, - PersonDetectionConfig, - ShotChangeDetectionConfig, - SpeechContext, - SpeechRecognitionAlternative, - SpeechTranscription, - SpeechTranscriptionConfig, - TextAnnotation, - TextDetectionConfig, - TextFrame, - TextSegment, - TimestampedObject, - Track, - VideoAnnotationProgress, - VideoAnnotationResults, - VideoContext, - VideoSegment, - WordInfo, - Feature, - LabelDetectionMode, - Likelihood, -) - -__all__ = ( - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'DetectedAttribute', - 'DetectedLandmark', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'FaceAnnotation', - 'FaceDetectionAnnotation', - 'FaceDetectionConfig', - 'FaceFrame', - 'FaceSegment', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'LogoRecognitionAnnotation', - 'NormalizedBoundingBox', - 'NormalizedBoundingPoly', - 'NormalizedVertex', - 'ObjectTrackingAnnotation', - 'ObjectTrackingConfig', - 'ObjectTrackingFrame', - 'PersonDetectionAnnotation', - 'PersonDetectionConfig', - 'ShotChangeDetectionConfig', - 'SpeechContext', - 'SpeechRecognitionAlternative', - 'SpeechTranscription', - 'SpeechTranscriptionConfig', - 'TextAnnotation', - 'TextDetectionConfig', - 'TextFrame', - 'TextSegment', - 'TimestampedObject', - 'Track', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'WordInfo', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py b/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py deleted file mode 100644 index e4fb5f23..00000000 --- a/owl-bot-staging/v1/google/cloud/videointelligence_v1/types/video_intelligence.py +++ /dev/null @@ -1,1689 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.videointelligence.v1', - manifest={ - 'Feature', - 'LabelDetectionMode', - 'Likelihood', - 'AnnotateVideoRequest', - 'VideoContext', - 'LabelDetectionConfig', - 'ShotChangeDetectionConfig', - 'ObjectTrackingConfig', - 'FaceDetectionConfig', - 'PersonDetectionConfig', - 'ExplicitContentDetectionConfig', - 'TextDetectionConfig', - 'VideoSegment', - 'LabelSegment', - 'LabelFrame', - 'Entity', - 'LabelAnnotation', - 'ExplicitContentFrame', - 'ExplicitContentAnnotation', - 'NormalizedBoundingBox', - 'FaceDetectionAnnotation', - 'PersonDetectionAnnotation', - 'FaceSegment', - 'FaceFrame', - 'FaceAnnotation', - 'TimestampedObject', - 'Track', - 'DetectedAttribute', - 'DetectedLandmark', - 'VideoAnnotationResults', - 'AnnotateVideoResponse', - 'VideoAnnotationProgress', - 'AnnotateVideoProgress', - 'SpeechTranscriptionConfig', - 'SpeechContext', - 'SpeechTranscription', - 'SpeechRecognitionAlternative', - 'WordInfo', - 'NormalizedVertex', - 'NormalizedBoundingPoly', - 'TextSegment', - 'TextFrame', - 'TextAnnotation', - 'ObjectTrackingFrame', - 'ObjectTrackingAnnotation', - 'LogoRecognitionAnnotation', - }, -) - - -class Feature(proto.Enum): - r"""Video annotation feature.""" - FEATURE_UNSPECIFIED = 0 - LABEL_DETECTION = 1 - SHOT_CHANGE_DETECTION = 2 - EXPLICIT_CONTENT_DETECTION = 3 - FACE_DETECTION = 4 - SPEECH_TRANSCRIPTION = 6 - TEXT_DETECTION = 7 - OBJECT_TRACKING = 9 - LOGO_RECOGNITION = 12 - PERSON_DETECTION = 14 - - -class LabelDetectionMode(proto.Enum): - r"""Label detection mode.""" - LABEL_DETECTION_MODE_UNSPECIFIED = 0 - SHOT_MODE = 1 - FRAME_MODE = 2 - SHOT_AND_FRAME_MODE = 3 - - -class Likelihood(proto.Enum): - r"""Bucketized representation of likelihood.""" - LIKELIHOOD_UNSPECIFIED = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class AnnotateVideoRequest(proto.Message): - r"""Video annotation request. - - Attributes: - input_uri (str): - Input video location. Currently, only `Cloud - Storage `__ URIs are - supported. URIs must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - To identify multiple videos, a video URI may include - wildcards in the ``object-id``. Supported wildcards: '*' to - match 0 or more characters; '?' to match 1 character. If - unset, the input video should be embedded in the request as - ``input_content``. If set, ``input_content`` must be unset. - input_content (bytes): - The video data bytes. If unset, the input video(s) should be - specified via the ``input_uri``. If set, ``input_uri`` must - be unset. - features (Sequence[google.cloud.videointelligence_v1.types.Feature]): - Required. Requested video annotation - features. - video_context (google.cloud.videointelligence_v1.types.VideoContext): - Additional video context and/or feature- - pecific parameters. - output_uri (str): - Optional. Location where the output (in JSON format) should - be stored. Currently, only `Cloud - Storage `__ URIs are - supported. These must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - location_id (str): - Optional. Cloud region where annotation should take place. - Supported cloud regions are: ``us-east1``, ``us-west1``, - ``europe-west1``, ``asia-east1``. If no region is specified, - the region will be determined based on video file location. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - input_content = proto.Field( - proto.BYTES, - number=6, - ) - features = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Feature', - ) - video_context = proto.Field( - proto.MESSAGE, - number=3, - message='VideoContext', - ) - output_uri = proto.Field( - proto.STRING, - number=4, - ) - location_id = proto.Field( - proto.STRING, - number=5, - ) - - -class VideoContext(proto.Message): - r"""Video context and/or feature-specific parameters. - - Attributes: - segments (Sequence[google.cloud.videointelligence_v1.types.VideoSegment]): - Video segments to annotate. The segments may - overlap and are not required to be contiguous or - span the whole video. If unspecified, each video - is treated as a single segment. - label_detection_config (google.cloud.videointelligence_v1.types.LabelDetectionConfig): - Config for LABEL_DETECTION. - shot_change_detection_config (google.cloud.videointelligence_v1.types.ShotChangeDetectionConfig): - Config for SHOT_CHANGE_DETECTION. - explicit_content_detection_config (google.cloud.videointelligence_v1.types.ExplicitContentDetectionConfig): - Config for EXPLICIT_CONTENT_DETECTION. - face_detection_config (google.cloud.videointelligence_v1.types.FaceDetectionConfig): - Config for FACE_DETECTION. - speech_transcription_config (google.cloud.videointelligence_v1.types.SpeechTranscriptionConfig): - Config for SPEECH_TRANSCRIPTION. - text_detection_config (google.cloud.videointelligence_v1.types.TextDetectionConfig): - Config for TEXT_DETECTION. - person_detection_config (google.cloud.videointelligence_v1.types.PersonDetectionConfig): - Config for PERSON_DETECTION. - object_tracking_config (google.cloud.videointelligence_v1.types.ObjectTrackingConfig): - Config for OBJECT_TRACKING. - """ - - segments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - label_detection_config = proto.Field( - proto.MESSAGE, - number=2, - message='LabelDetectionConfig', - ) - shot_change_detection_config = proto.Field( - proto.MESSAGE, - number=3, - message='ShotChangeDetectionConfig', - ) - explicit_content_detection_config = proto.Field( - proto.MESSAGE, - number=4, - message='ExplicitContentDetectionConfig', - ) - face_detection_config = proto.Field( - proto.MESSAGE, - number=5, - message='FaceDetectionConfig', - ) - speech_transcription_config = proto.Field( - proto.MESSAGE, - number=6, - message='SpeechTranscriptionConfig', - ) - text_detection_config = proto.Field( - proto.MESSAGE, - number=8, - message='TextDetectionConfig', - ) - person_detection_config = proto.Field( - proto.MESSAGE, - number=11, - message='PersonDetectionConfig', - ) - object_tracking_config = proto.Field( - proto.MESSAGE, - number=13, - message='ObjectTrackingConfig', - ) - - -class LabelDetectionConfig(proto.Message): - r"""Config for LABEL_DETECTION. - - Attributes: - label_detection_mode (google.cloud.videointelligence_v1.types.LabelDetectionMode): - What labels should be detected with LABEL_DETECTION, in - addition to video-level labels or segment-level labels. If - unspecified, defaults to ``SHOT_MODE``. - stationary_camera (bool): - Whether the video has been shot from a stationary (i.e., - non-moving) camera. When set to true, might improve - detection accuracy for moving objects. Should be used with - ``SHOT_AND_FRAME_MODE`` enabled. - model (str): - Model to use for label detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - frame_confidence_threshold (float): - The confidence threshold we perform filtering on the labels - from frame-level detection. If not set, it is set to 0.4 by - default. The valid range for this threshold is [0.1, 0.9]. - Any value set outside of this range will be clipped. Note: - For best results, follow the default threshold. We will - update the default threshold everytime when we release a new - model. - video_confidence_threshold (float): - The confidence threshold we perform filtering on the labels - from video-level and shot-level detections. If not set, it's - set to 0.3 by default. The valid range for this threshold is - [0.1, 0.9]. Any value set outside of this range will be - clipped. Note: For best results, follow the default - threshold. We will update the default threshold everytime - when we release a new model. - """ - - label_detection_mode = proto.Field( - proto.ENUM, - number=1, - enum='LabelDetectionMode', - ) - stationary_camera = proto.Field( - proto.BOOL, - number=2, - ) - model = proto.Field( - proto.STRING, - number=3, - ) - frame_confidence_threshold = proto.Field( - proto.FLOAT, - number=4, - ) - video_confidence_threshold = proto.Field( - proto.FLOAT, - number=5, - ) - - -class ShotChangeDetectionConfig(proto.Message): - r"""Config for SHOT_CHANGE_DETECTION. - - Attributes: - model (str): - Model to use for shot change detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class ObjectTrackingConfig(proto.Message): - r"""Config for OBJECT_TRACKING. - - Attributes: - model (str): - Model to use for object tracking. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class FaceDetectionConfig(proto.Message): - r"""Config for FACE_DETECTION. - - Attributes: - model (str): - Model to use for face detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - include_bounding_boxes (bool): - Whether bounding boxes are included in the - face annotation output. - include_attributes (bool): - Whether to enable face attributes detection, such as - glasses, dark_glasses, mouth_open etc. Ignored if - 'include_bounding_boxes' is set to false. - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - include_bounding_boxes = proto.Field( - proto.BOOL, - number=2, - ) - include_attributes = proto.Field( - proto.BOOL, - number=5, - ) - - -class PersonDetectionConfig(proto.Message): - r"""Config for PERSON_DETECTION. - - Attributes: - include_bounding_boxes (bool): - Whether bounding boxes are included in the - person detection annotation output. - include_pose_landmarks (bool): - Whether to enable pose landmarks detection. Ignored if - 'include_bounding_boxes' is set to false. - include_attributes (bool): - Whether to enable person attributes detection, such as cloth - color (black, blue, etc), type (coat, dress, etc), pattern - (plain, floral, etc), hair, etc. Ignored if - 'include_bounding_boxes' is set to false. - """ - - include_bounding_boxes = proto.Field( - proto.BOOL, - number=1, - ) - include_pose_landmarks = proto.Field( - proto.BOOL, - number=2, - ) - include_attributes = proto.Field( - proto.BOOL, - number=3, - ) - - -class ExplicitContentDetectionConfig(proto.Message): - r"""Config for EXPLICIT_CONTENT_DETECTION. - - Attributes: - model (str): - Model to use for explicit content detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class TextDetectionConfig(proto.Message): - r"""Config for TEXT_DETECTION. - - Attributes: - language_hints (Sequence[str]): - Language hint can be specified if the - language to be detected is known a priori. It - can increase the accuracy of the detection. - Language hint must be language code in BCP-47 - format. - - Automatic language detection is performed if no - hint is provided. - model (str): - Model to use for text detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - language_hints = proto.RepeatedField( - proto.STRING, - number=1, - ) - model = proto.Field( - proto.STRING, - number=2, - ) - - -class VideoSegment(proto.Message): - r"""Video segment. - - Attributes: - start_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the start of the segment - (inclusive). - end_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the end of the segment - (inclusive). - """ - - start_time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class LabelSegment(proto.Message): - r"""Video segment level annotation results for label detection. - - Attributes: - segment (google.cloud.videointelligence_v1.types.VideoSegment): - Video segment where a label was detected. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class LabelFrame(proto.Message): - r"""Video frame level annotation results for label detection. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class Entity(proto.Message): - r"""Detected entity from video analysis. - - Attributes: - entity_id (str): - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search - API `__. - description (str): - Textual description, e.g., ``Fixed-gear bicycle``. - language_code (str): - Language code for ``description`` in BCP-47 format. - """ - - entity_id = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class LabelAnnotation(proto.Message): - r"""Label annotation. - - Attributes: - entity (google.cloud.videointelligence_v1.types.Entity): - Detected entity. - category_entities (Sequence[google.cloud.videointelligence_v1.types.Entity]): - Common categories for the detected entity. For example, when - the label is ``Terrier``, the category is likely ``dog``. - And in some cases there might be more than one categories - e.g., ``Terrier`` could also be a ``pet``. - segments (Sequence[google.cloud.videointelligence_v1.types.LabelSegment]): - All video segments where a label was - detected. - frames (Sequence[google.cloud.videointelligence_v1.types.LabelFrame]): - All video frames where a label was detected. - version (str): - Feature version. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - category_entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Entity', - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelSegment', - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelFrame', - ) - version = proto.Field( - proto.STRING, - number=5, - ) - - -class ExplicitContentFrame(proto.Message): - r"""Video frame level annotation results for explicit content. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - pornography_likelihood (google.cloud.videointelligence_v1.types.Likelihood): - Likelihood of the pornography content.. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - pornography_likelihood = proto.Field( - proto.ENUM, - number=2, - enum='Likelihood', - ) - - -class ExplicitContentAnnotation(proto.Message): - r"""Explicit content annotation (based on per-frame visual - signals only). If no explicit content has been detected in a - frame, no annotations are present for that frame. - - Attributes: - frames (Sequence[google.cloud.videointelligence_v1.types.ExplicitContentFrame]): - All video frames where explicit content was - detected. - version (str): - Feature version. - """ - - frames = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExplicitContentFrame', - ) - version = proto.Field( - proto.STRING, - number=2, - ) - - -class NormalizedBoundingBox(proto.Message): - r"""Normalized bounding box. The normalized vertex coordinates are - relative to the original image. Range: [0, 1]. - - Attributes: - left (float): - Left X coordinate. - top (float): - Top Y coordinate. - right (float): - Right X coordinate. - bottom (float): - Bottom Y coordinate. - """ - - left = proto.Field( - proto.FLOAT, - number=1, - ) - top = proto.Field( - proto.FLOAT, - number=2, - ) - right = proto.Field( - proto.FLOAT, - number=3, - ) - bottom = proto.Field( - proto.FLOAT, - number=4, - ) - - -class FaceDetectionAnnotation(proto.Message): - r"""Face detection annotation. - - Attributes: - tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): - The face tracks with attributes. - thumbnail (bytes): - The thumbnail of a person's face. - version (str): - Feature version. - """ - - tracks = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Track', - ) - thumbnail = proto.Field( - proto.BYTES, - number=4, - ) - version = proto.Field( - proto.STRING, - number=5, - ) - - -class PersonDetectionAnnotation(proto.Message): - r"""Person detection annotation per video. - - Attributes: - tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): - The detected tracks of a person. - version (str): - Feature version. - """ - - tracks = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Track', - ) - version = proto.Field( - proto.STRING, - number=2, - ) - - -class FaceSegment(proto.Message): - r"""Video segment level annotation results for face detection. - - Attributes: - segment (google.cloud.videointelligence_v1.types.VideoSegment): - Video segment where a face was detected. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - - -class FaceFrame(proto.Message): - r"""Deprecated. No effect. - - Attributes: - normalized_bounding_boxes (Sequence[google.cloud.videointelligence_v1.types.NormalizedBoundingBox]): - Normalized Bounding boxes in a frame. - There can be more than one boxes if the same - face is detected in multiple locations within - the current frame. - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - """ - - normalized_bounding_boxes = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NormalizedBoundingBox', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class FaceAnnotation(proto.Message): - r"""Deprecated. No effect. - - Attributes: - thumbnail (bytes): - Thumbnail of a representative face view (in - JPEG format). - segments (Sequence[google.cloud.videointelligence_v1.types.FaceSegment]): - All video segments where a face was detected. - frames (Sequence[google.cloud.videointelligence_v1.types.FaceFrame]): - All video frames where a face was detected. - """ - - thumbnail = proto.Field( - proto.BYTES, - number=1, - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='FaceSegment', - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='FaceFrame', - ) - - -class TimestampedObject(proto.Message): - r"""For tracking related features. An object at time_offset with - attributes, and located with normalized_bounding_box. - - Attributes: - normalized_bounding_box (google.cloud.videointelligence_v1.types.NormalizedBoundingBox): - Normalized Bounding box in a frame, where the - object is located. - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - object. - attributes (Sequence[google.cloud.videointelligence_v1.types.DetectedAttribute]): - Optional. The attributes of the object in the - bounding box. - landmarks (Sequence[google.cloud.videointelligence_v1.types.DetectedLandmark]): - Optional. The detected landmarks. - """ - - normalized_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingBox', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - attributes = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='DetectedAttribute', - ) - landmarks = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='DetectedLandmark', - ) - - -class Track(proto.Message): - r"""A track of an object instance. - - Attributes: - segment (google.cloud.videointelligence_v1.types.VideoSegment): - Video segment of a track. - timestamped_objects (Sequence[google.cloud.videointelligence_v1.types.TimestampedObject]): - The object with timestamp and attributes per - frame in the track. - attributes (Sequence[google.cloud.videointelligence_v1.types.DetectedAttribute]): - Optional. Attributes in the track level. - confidence (float): - Optional. The confidence score of the tracked - object. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - timestamped_objects = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TimestampedObject', - ) - attributes = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='DetectedAttribute', - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - - -class DetectedAttribute(proto.Message): - r"""A generic detected attribute represented by name in string - format. - - Attributes: - name (str): - The name of the attribute, for example, glasses, - dark_glasses, mouth_open. A full list of supported type - names will be provided in the document. - confidence (float): - Detected attribute confidence. Range [0, 1]. - value (str): - Text value of the detection result. For - example, the value for "HairColor" can be - "black", "blonde", etc. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - value = proto.Field( - proto.STRING, - number=3, - ) - - -class DetectedLandmark(proto.Message): - r"""A generic detected landmark represented by name in string - format and a 2D location. - - Attributes: - name (str): - The name of this landmark, for example, left_hand, - right_shoulder. - point (google.cloud.videointelligence_v1.types.NormalizedVertex): - The 2D point of the detected landmark using - the normalized image coordindate system. The - normalized coordinates have the range from 0 to - 1. - confidence (float): - The confidence score of the detected landmark. Range [0, 1]. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - point = proto.Field( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - confidence = proto.Field( - proto.FLOAT, - number=3, - ) - - -class VideoAnnotationResults(proto.Message): - r"""Annotation results for a single video. - - Attributes: - input_uri (str): - Video file location in `Cloud - Storage `__. - segment (google.cloud.videointelligence_v1.types.VideoSegment): - Video segment on which the annotation is run. - segment_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): - Topical label annotations on video level or - user-specified segment level. There is exactly - one element for each unique label. - segment_presence_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): - Presence label annotations on video level or user-specified - segment level. There is exactly one element for each unique - label. Compared to the existing topical - ``segment_label_annotations``, this field presents more - fine-grained, segment-level labels detected in video content - and is made available only when the client sets - ``LabelDetectionConfig.model`` to "builtin/latest" in the - request. - shot_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): - Topical label annotations on shot level. - There is exactly one element for each unique - label. - shot_presence_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): - Presence label annotations on shot level. There is exactly - one element for each unique label. Compared to the existing - topical ``shot_label_annotations``, this field presents more - fine-grained, shot-level labels detected in video content - and is made available only when the client sets - ``LabelDetectionConfig.model`` to "builtin/latest" in the - request. - frame_label_annotations (Sequence[google.cloud.videointelligence_v1.types.LabelAnnotation]): - Label annotations on frame level. - There is exactly one element for each unique - label. - face_annotations (Sequence[google.cloud.videointelligence_v1.types.FaceAnnotation]): - Deprecated. Please use ``face_detection_annotations`` - instead. - face_detection_annotations (Sequence[google.cloud.videointelligence_v1.types.FaceDetectionAnnotation]): - Face detection annotations. - shot_annotations (Sequence[google.cloud.videointelligence_v1.types.VideoSegment]): - Shot annotations. Each shot is represented as - a video segment. - explicit_annotation (google.cloud.videointelligence_v1.types.ExplicitContentAnnotation): - Explicit content annotation. - speech_transcriptions (Sequence[google.cloud.videointelligence_v1.types.SpeechTranscription]): - Speech transcription. - text_annotations (Sequence[google.cloud.videointelligence_v1.types.TextAnnotation]): - OCR text detection and tracking. - Annotations for list of detected text snippets. - Each will have list of frame information - associated with it. - object_annotations (Sequence[google.cloud.videointelligence_v1.types.ObjectTrackingAnnotation]): - Annotations for list of objects detected and - tracked in video. - logo_recognition_annotations (Sequence[google.cloud.videointelligence_v1.types.LogoRecognitionAnnotation]): - Annotations for list of logos detected, - tracked and recognized in video. - person_detection_annotations (Sequence[google.cloud.videointelligence_v1.types.PersonDetectionAnnotation]): - Person detection annotations. - error (google.rpc.status_pb2.Status): - If set, indicates an error. Note that for a single - ``AnnotateVideoRequest`` some videos may succeed and some - may fail. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - segment = proto.Field( - proto.MESSAGE, - number=10, - message='VideoSegment', - ) - segment_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='LabelAnnotation', - ) - segment_presence_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=23, - message='LabelAnnotation', - ) - shot_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelAnnotation', - ) - shot_presence_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=24, - message='LabelAnnotation', - ) - frame_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelAnnotation', - ) - face_annotations = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='FaceAnnotation', - ) - face_detection_annotations = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='FaceDetectionAnnotation', - ) - shot_annotations = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='VideoSegment', - ) - explicit_annotation = proto.Field( - proto.MESSAGE, - number=7, - message='ExplicitContentAnnotation', - ) - speech_transcriptions = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='SpeechTranscription', - ) - text_annotations = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='TextAnnotation', - ) - object_annotations = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='ObjectTrackingAnnotation', - ) - logo_recognition_annotations = proto.RepeatedField( - proto.MESSAGE, - number=19, - message='LogoRecognitionAnnotation', - ) - person_detection_annotations = proto.RepeatedField( - proto.MESSAGE, - number=20, - message='PersonDetectionAnnotation', - ) - error = proto.Field( - proto.MESSAGE, - number=9, - message=status_pb2.Status, - ) - - -class AnnotateVideoResponse(proto.Message): - r"""Video annotation response. Included in the ``response`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_results (Sequence[google.cloud.videointelligence_v1.types.VideoAnnotationResults]): - Annotation results for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationResults', - ) - - -class VideoAnnotationProgress(proto.Message): - r"""Annotation progress for a single video. - - Attributes: - input_uri (str): - Video file location in `Cloud - Storage `__. - progress_percent (int): - Approximate percentage processed thus far. - Guaranteed to be 100 when fully processed. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the request was received. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Time of the most recent update. - feature (google.cloud.videointelligence_v1.types.Feature): - Specifies which feature is being tracked if - the request contains more than one feature. - segment (google.cloud.videointelligence_v1.types.VideoSegment): - Specifies which segment is being tracked if - the request contains more than one segment. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - progress_percent = proto.Field( - proto.INT32, - number=2, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - feature = proto.Field( - proto.ENUM, - number=5, - enum='Feature', - ) - segment = proto.Field( - proto.MESSAGE, - number=6, - message='VideoSegment', - ) - - -class AnnotateVideoProgress(proto.Message): - r"""Video annotation progress. Included in the ``metadata`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_progress (Sequence[google.cloud.videointelligence_v1.types.VideoAnnotationProgress]): - Progress metadata for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_progress = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationProgress', - ) - - -class SpeechTranscriptionConfig(proto.Message): - r"""Config for SPEECH_TRANSCRIPTION. - - Attributes: - language_code (str): - Required. *Required* The language of the supplied audio as a - `BCP-47 `__ - language tag. Example: "en-US". See `Language - Support `__ - for a list of the currently supported language codes. - max_alternatives (int): - Optional. Maximum number of recognition hypotheses to be - returned. Specifically, the maximum number of - ``SpeechRecognitionAlternative`` messages within each - ``SpeechTranscription``. The server may return fewer than - ``max_alternatives``. Valid values are ``0``-``30``. A value - of ``0`` or ``1`` will return a maximum of one. If omitted, - will return a maximum of one. - filter_profanity (bool): - Optional. If set to ``true``, the server will attempt to - filter out profanities, replacing all but the initial - character in each filtered word with asterisks, e.g. "f***". - If set to ``false`` or omitted, profanities won't be - filtered out. - speech_contexts (Sequence[google.cloud.videointelligence_v1.types.SpeechContext]): - Optional. A means to provide context to - assist the speech recognition. - enable_automatic_punctuation (bool): - Optional. If 'true', adds punctuation to - recognition result hypotheses. This feature is - only available in select languages. Setting this - for requests in other languages has no effect at - all. The default 'false' value does not add - punctuation to result hypotheses. NOTE: "This is - currently offered as an experimental service, - complimentary to all users. In the future this - may be exclusively available as a premium - feature.". - audio_tracks (Sequence[int]): - Optional. For file formats, such as MXF or - MKV, supporting multiple audio tracks, specify - up to two tracks. Default: track 0. - enable_speaker_diarization (bool): - Optional. If 'true', enables speaker detection for each - recognized word in the top alternative of the recognition - result using a speaker_tag provided in the WordInfo. Note: - When this is true, we send all the words from the beginning - of the audio for the top alternative in every consecutive - response. This is done in order to improve our speaker tags - as our models learn to identify the speakers in the - conversation over time. - diarization_speaker_count (int): - Optional. If set, specifies the estimated number of speakers - in the conversation. If not set, defaults to '2'. Ignored - unless enable_speaker_diarization is set to true. - enable_word_confidence (bool): - Optional. If ``true``, the top result includes a list of - words and the confidence for those words. If ``false``, no - word-level confidence information is returned. The default - is ``false``. - """ - - language_code = proto.Field( - proto.STRING, - number=1, - ) - max_alternatives = proto.Field( - proto.INT32, - number=2, - ) - filter_profanity = proto.Field( - proto.BOOL, - number=3, - ) - speech_contexts = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SpeechContext', - ) - enable_automatic_punctuation = proto.Field( - proto.BOOL, - number=5, - ) - audio_tracks = proto.RepeatedField( - proto.INT32, - number=6, - ) - enable_speaker_diarization = proto.Field( - proto.BOOL, - number=7, - ) - diarization_speaker_count = proto.Field( - proto.INT32, - number=8, - ) - enable_word_confidence = proto.Field( - proto.BOOL, - number=9, - ) - - -class SpeechContext(proto.Message): - r"""Provides "hints" to the speech recognizer to favor specific - words and phrases in the results. - - Attributes: - phrases (Sequence[str]): - Optional. A list of strings containing words and phrases - "hints" so that the speech recognition is more likely to - recognize them. This can be used to improve the accuracy for - specific words and phrases, for example, if specific - commands are typically spoken by the user. This can also be - used to add additional words to the vocabulary of the - recognizer. See `usage - limits `__. - """ - - phrases = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class SpeechTranscription(proto.Message): - r"""A speech recognition result corresponding to a portion of the - audio. - - Attributes: - alternatives (Sequence[google.cloud.videointelligence_v1.types.SpeechRecognitionAlternative]): - May contain one or more recognition hypotheses (up to the - maximum specified in ``max_alternatives``). These - alternatives are ordered in terms of accuracy, with the top - (first) alternative being the most probable, as ranked by - the recognizer. - language_code (str): - Output only. The - `BCP-47 `__ - language tag of the language in this result. This language - code was detected to have the most likelihood of being - spoken in the audio. - """ - - alternatives = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SpeechRecognitionAlternative', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class SpeechRecognitionAlternative(proto.Message): - r"""Alternative hypotheses (a.k.a. n-best list). - - Attributes: - transcript (str): - Transcript text representing the words that - the user spoke. - confidence (float): - Output only. The confidence estimate between 0.0 and 1.0. A - higher number indicates an estimated greater likelihood that - the recognized words are correct. This field is set only for - the top alternative. This field is not guaranteed to be - accurate and users should not rely on it to be always - provided. The default of 0.0 is a sentinel value indicating - ``confidence`` was not set. - words (Sequence[google.cloud.videointelligence_v1.types.WordInfo]): - Output only. A list of word-specific information for each - recognized word. Note: When ``enable_speaker_diarization`` - is set to true, you will see all the words from the - beginning of the audio. - """ - - transcript = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - words = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='WordInfo', - ) - - -class WordInfo(proto.Message): - r"""Word-specific information for recognized words. Word information is - only included in the response when certain request parameters are - set, such as ``enable_word_time_offsets``. - - Attributes: - start_time (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the audio, and - corresponding to the start of the spoken word. This field is - only set if ``enable_word_time_offsets=true`` and only in - the top hypothesis. This is an experimental feature and the - accuracy of the time offset can vary. - end_time (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the audio, and - corresponding to the end of the spoken word. This field is - only set if ``enable_word_time_offsets=true`` and only in - the top hypothesis. This is an experimental feature and the - accuracy of the time offset can vary. - word (str): - The word corresponding to this set of - information. - confidence (float): - Output only. The confidence estimate between 0.0 and 1.0. A - higher number indicates an estimated greater likelihood that - the recognized words are correct. This field is set only for - the top alternative. This field is not guaranteed to be - accurate and users should not rely on it to be always - provided. The default of 0.0 is a sentinel value indicating - ``confidence`` was not set. - speaker_tag (int): - Output only. A distinct integer value is assigned for every - speaker within the audio. This field specifies which one of - those speakers was detected to have spoken this word. Value - ranges from 1 up to diarization_speaker_count, and is only - set if speaker diarization is enabled. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - word = proto.Field( - proto.STRING, - number=3, - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - speaker_tag = proto.Field( - proto.INT32, - number=5, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate. - """ - - x = proto.Field( - proto.FLOAT, - number=1, - ) - y = proto.Field( - proto.FLOAT, - number=2, - ) - - -class NormalizedBoundingPoly(proto.Message): - r"""Normalized bounding polygon for text (that might not be aligned with - axis). Contains list of the corner points in clockwise order - starting from top-left corner. For example, for a rectangular - bounding box: When the text is horizontal it might look like: 0----1 - \| \| 3----2 - - When it's clockwise rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 - - and the vertex order will still be (0, 1, 2, 3). Note that values - can be less than 0, or greater than 1 due to trignometric - calculations for location of the box. - - Attributes: - vertices (Sequence[google.cloud.videointelligence_v1.types.NormalizedVertex]): - Normalized vertices of the bounding polygon. - """ - - vertices = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NormalizedVertex', - ) - - -class TextSegment(proto.Message): - r"""Video segment level annotation results for text detection. - - Attributes: - segment (google.cloud.videointelligence_v1.types.VideoSegment): - Video segment where a text snippet was - detected. - confidence (float): - Confidence for the track of detected text. It - is calculated as the highest over all frames - where OCR detected text appears. - frames (Sequence[google.cloud.videointelligence_v1.types.TextFrame]): - Information related to the frames where OCR - detected text appears. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='TextFrame', - ) - - -class TextFrame(proto.Message): - r"""Video frame level annotation results for text annotation - (OCR). Contains information regarding timestamp and bounding box - locations for the frames containing detected OCR text snippets. - - Attributes: - rotated_bounding_box (google.cloud.videointelligence_v1.types.NormalizedBoundingPoly): - Bounding polygon of the detected text for - this frame. - time_offset (google.protobuf.duration_pb2.Duration): - Timestamp of this frame. - """ - - rotated_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingPoly', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class TextAnnotation(proto.Message): - r"""Annotations related to one detected OCR text snippet. This - will contain the corresponding text, confidence value, and frame - level information for each detection. - - Attributes: - text (str): - The detected text. - segments (Sequence[google.cloud.videointelligence_v1.types.TextSegment]): - All video segments where OCR detected text - appears. - version (str): - Feature version. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TextSegment', - ) - version = proto.Field( - proto.STRING, - number=3, - ) - - -class ObjectTrackingFrame(proto.Message): - r"""Video frame level annotations for object detection and - tracking. This field stores per frame location, time offset, and - confidence. - - Attributes: - normalized_bounding_box (google.cloud.videointelligence_v1.types.NormalizedBoundingBox): - The normalized bounding box location of this - object track for the frame. - time_offset (google.protobuf.duration_pb2.Duration): - The timestamp of the frame in microseconds. - """ - - normalized_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingBox', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class ObjectTrackingAnnotation(proto.Message): - r"""Annotations corresponding to one tracked object. - - Attributes: - segment (google.cloud.videointelligence_v1.types.VideoSegment): - Non-streaming batch mode ONLY. - Each object track corresponds to one video - segment where it appears. - track_id (int): - Streaming mode ONLY. In streaming mode, we do not know the - end time of a tracked object before it is completed. Hence, - there is no VideoSegment info returned. Instead, we provide - a unique identifiable integer track_id so that the customers - can correlate the results of the ongoing - ObjectTrackAnnotation of the same track_id over time. - entity (google.cloud.videointelligence_v1.types.Entity): - Entity to specify the object category that - this track is labeled as. - confidence (float): - Object category's labeling confidence of this - track. - frames (Sequence[google.cloud.videointelligence_v1.types.ObjectTrackingFrame]): - Information corresponding to all frames where - this object track appears. Non-streaming batch - mode: it may be one or multiple - ObjectTrackingFrame messages in frames. - Streaming mode: it can only be one - ObjectTrackingFrame message in frames. - version (str): - Feature version. - """ - - segment = proto.Field( - proto.MESSAGE, - number=3, - oneof='track_info', - message='VideoSegment', - ) - track_id = proto.Field( - proto.INT64, - number=5, - oneof='track_info', - ) - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ObjectTrackingFrame', - ) - version = proto.Field( - proto.STRING, - number=6, - ) - - -class LogoRecognitionAnnotation(proto.Message): - r"""Annotation corresponding to one detected, tracked and - recognized logo class. - - Attributes: - entity (google.cloud.videointelligence_v1.types.Entity): - Entity category information to specify the - logo class that all the logo tracks within this - LogoRecognitionAnnotation are recognized as. - tracks (Sequence[google.cloud.videointelligence_v1.types.Track]): - All logo tracks where the recognized logo - appears. Each track corresponds to one logo - instance appearing in consecutive frames. - segments (Sequence[google.cloud.videointelligence_v1.types.VideoSegment]): - All video segments where the recognized logo - appears. There might be multiple instances of - the same logo class appearing in one - VideoSegment. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - tracks = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Track', - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='VideoSegment', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 6a8f2d45..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/videointelligence_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py deleted file mode 100644 index 7c1a29e9..00000000 --- a/owl-bot-staging/v1/scripts/fixup_videointelligence_v1_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class videointelligenceCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=videointelligenceCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the videointelligence client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 87b7ba3d..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-videointelligence', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py b/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py deleted file mode 100644 index 45358458..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py +++ /dev/null @@ -1,1177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.videointelligence_v1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient -from google.cloud.videointelligence_v1.services.video_intelligence_service import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1.services.video_intelligence_service import transports -from google.cloud.videointelligence_v1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.videointelligence_v1.types import video_intelligence -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_client_get_transport_class(): - transport = VideoIntelligenceServiceClient.get_transport_class() - available_transports = [ - transports.VideoIntelligenceServiceGrpcTransport, - ] - assert transport in available_transports - - transport = VideoIntelligenceServiceClient.get_transport_class("grpc") - assert transport == transports.VideoIntelligenceServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_video_intelligence_service_client_client_options_from_dict(): - with mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VideoIntelligenceServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_annotate_video_from_dict(): - test_annotate_video(request_type=dict) - - -def test_annotate_video_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - client.annotate_video() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - -@pytest.mark.asyncio -async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_annotate_video_async_from_dict(): - await test_annotate_video_async(request_type=dict) - - -def test_annotate_video_flattened(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -def test_annotate_video_flattened_error(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_error_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VideoIntelligenceServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VideoIntelligenceServiceGrpcTransport, - ) - -def test_video_intelligence_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_video_intelligence_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'annotate_video', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_video_intelligence_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "videointelligence.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="videointelligence.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_video_intelligence_service_host_no_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_host_with_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:8000' - -def test_video_intelligence_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_video_intelligence_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_video_intelligence_service_grpc_lro_client(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_video_intelligence_service_grpc_lro_async_client(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = VideoIntelligenceServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = VideoIntelligenceServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VideoIntelligenceServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = VideoIntelligenceServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = VideoIntelligenceServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = VideoIntelligenceServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = VideoIntelligenceServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = VideoIntelligenceServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = VideoIntelligenceServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1beta2/.coveragerc b/owl-bot-staging/v1beta2/.coveragerc deleted file mode 100644 index 45c608f8..00000000 --- a/owl-bot-staging/v1beta2/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/videointelligence/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1beta2/MANIFEST.in b/owl-bot-staging/v1beta2/MANIFEST.in deleted file mode 100644 index a12cb4f4..00000000 --- a/owl-bot-staging/v1beta2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/videointelligence *.py -recursive-include google/cloud/videointelligence_v1beta2 *.py diff --git a/owl-bot-staging/v1beta2/README.rst b/owl-bot-staging/v1beta2/README.rst deleted file mode 100644 index bedc3680..00000000 --- a/owl-bot-staging/v1beta2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Videointelligence API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Videointelligence API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1beta2/docs/conf.py b/owl-bot-staging/v1beta2/docs/conf.py deleted file mode 100644 index 7a82f64b..00000000 --- a/owl-bot-staging/v1beta2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-videointelligence documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-videointelligence" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-videointelligence-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-videointelligence.tex", - u"google-cloud-videointelligence Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-videointelligence", - u"Google Cloud Videointelligence Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-videointelligence", - u"google-cloud-videointelligence Documentation", - author, - "google-cloud-videointelligence", - "GAPIC library for Google Cloud Videointelligence API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1beta2/docs/index.rst b/owl-bot-staging/v1beta2/docs/index.rst deleted file mode 100644 index f473cb6a..00000000 --- a/owl-bot-staging/v1beta2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - videointelligence_v1beta2/services - videointelligence_v1beta2/types diff --git a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst deleted file mode 100644 index c8f45a1e..00000000 --- a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Videointelligence v1beta2 API -======================================================= -.. toctree:: - :maxdepth: 2 - - video_intelligence_service diff --git a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst deleted file mode 100644 index 62921eac..00000000 --- a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Videointelligence v1beta2 API -==================================================== - -.. automodule:: google.cloud.videointelligence_v1beta2.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst b/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst deleted file mode 100644 index ab6c31d3..00000000 --- a/owl-bot-staging/v1beta2/docs/videointelligence_v1beta2/video_intelligence_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -VideoIntelligenceService ------------------------------------------- - -.. automodule:: google.cloud.videointelligence_v1beta2.services.video_intelligence_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py deleted file mode 100644 index d69bd06c..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence/__init__.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.videointelligence_v1beta2.services.video_intelligence_service.client import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1beta2.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient - -from google.cloud.videointelligence_v1beta2.types.video_intelligence import AnnotateVideoProgress -from google.cloud.videointelligence_v1beta2.types.video_intelligence import AnnotateVideoRequest -from google.cloud.videointelligence_v1beta2.types.video_intelligence import AnnotateVideoResponse -from google.cloud.videointelligence_v1beta2.types.video_intelligence import Entity -from google.cloud.videointelligence_v1beta2.types.video_intelligence import ExplicitContentAnnotation -from google.cloud.videointelligence_v1beta2.types.video_intelligence import ExplicitContentDetectionConfig -from google.cloud.videointelligence_v1beta2.types.video_intelligence import ExplicitContentFrame -from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceAnnotation -from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceDetectionConfig -from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceFrame -from google.cloud.videointelligence_v1beta2.types.video_intelligence import FaceSegment -from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelAnnotation -from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelDetectionConfig -from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelFrame -from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelSegment -from google.cloud.videointelligence_v1beta2.types.video_intelligence import NormalizedBoundingBox -from google.cloud.videointelligence_v1beta2.types.video_intelligence import ShotChangeDetectionConfig -from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoAnnotationProgress -from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoAnnotationResults -from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoContext -from google.cloud.videointelligence_v1beta2.types.video_intelligence import VideoSegment -from google.cloud.videointelligence_v1beta2.types.video_intelligence import Feature -from google.cloud.videointelligence_v1beta2.types.video_intelligence import LabelDetectionMode -from google.cloud.videointelligence_v1beta2.types.video_intelligence import Likelihood - -__all__ = ('VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'FaceAnnotation', - 'FaceDetectionConfig', - 'FaceFrame', - 'FaceSegment', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'NormalizedBoundingBox', - 'ShotChangeDetectionConfig', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py deleted file mode 100644 index 19f1f67d..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.video_intelligence_service import VideoIntelligenceServiceClient -from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient - -from .types.video_intelligence import AnnotateVideoProgress -from .types.video_intelligence import AnnotateVideoRequest -from .types.video_intelligence import AnnotateVideoResponse -from .types.video_intelligence import Entity -from .types.video_intelligence import ExplicitContentAnnotation -from .types.video_intelligence import ExplicitContentDetectionConfig -from .types.video_intelligence import ExplicitContentFrame -from .types.video_intelligence import FaceAnnotation -from .types.video_intelligence import FaceDetectionConfig -from .types.video_intelligence import FaceFrame -from .types.video_intelligence import FaceSegment -from .types.video_intelligence import LabelAnnotation -from .types.video_intelligence import LabelDetectionConfig -from .types.video_intelligence import LabelFrame -from .types.video_intelligence import LabelSegment -from .types.video_intelligence import NormalizedBoundingBox -from .types.video_intelligence import ShotChangeDetectionConfig -from .types.video_intelligence import VideoAnnotationProgress -from .types.video_intelligence import VideoAnnotationResults -from .types.video_intelligence import VideoContext -from .types.video_intelligence import VideoSegment -from .types.video_intelligence import Feature -from .types.video_intelligence import LabelDetectionMode -from .types.video_intelligence import Likelihood - -__all__ = ( - 'VideoIntelligenceServiceAsyncClient', -'AnnotateVideoProgress', -'AnnotateVideoRequest', -'AnnotateVideoResponse', -'Entity', -'ExplicitContentAnnotation', -'ExplicitContentDetectionConfig', -'ExplicitContentFrame', -'FaceAnnotation', -'FaceDetectionConfig', -'FaceFrame', -'FaceSegment', -'Feature', -'LabelAnnotation', -'LabelDetectionConfig', -'LabelDetectionMode', -'LabelFrame', -'LabelSegment', -'Likelihood', -'NormalizedBoundingBox', -'ShotChangeDetectionConfig', -'VideoAnnotationProgress', -'VideoAnnotationResults', -'VideoContext', -'VideoIntelligenceServiceClient', -'VideoSegment', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json deleted file mode 100644 index 478a3473..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/gapic_metadata.json +++ /dev/null @@ -1,33 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.videointelligence_v1beta2", - "protoPackage": "google.cloud.videointelligence.v1beta2", - "schema": "1.0", - "services": { - "VideoIntelligenceService": { - "clients": { - "grpc": { - "libraryClient": "VideoIntelligenceServiceClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VideoIntelligenceServiceAsyncClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py deleted file mode 100644 index 4094cd26..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import VideoIntelligenceServiceClient -from .async_client import VideoIntelligenceServiceAsyncClient - -__all__ = ( - 'VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py deleted file mode 100644 index f50b7b49..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/async_client.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1beta2.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport -from .client import VideoIntelligenceServiceClient - - -class VideoIntelligenceServiceAsyncClient: - """Service that implements Google Cloud Video Intelligence API.""" - - _client: VideoIntelligenceServiceClient - - DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) - common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) - parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) - common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) - parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = VideoIntelligenceServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def annotate_video(self, - request: video_intelligence.AnnotateVideoRequest = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (:class:`google.cloud.videointelligence_v1beta2.types.AnnotateVideoRequest`): - The request object. Video annotation request. - input_uri (:class:`str`): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and - thus identify multiple videos. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - should be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (:class:`Sequence[google.cloud.videointelligence_v1beta2.types.Feature]`): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1beta2.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = video_intelligence.AnnotateVideoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features: - request.features.extend(features) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceAsyncClient", -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py deleted file mode 100644 index f5828e59..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/client.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1beta2.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VideoIntelligenceServiceGrpcTransport -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -class VideoIntelligenceServiceClientMeta(type): - """Metaclass for the VideoIntelligenceService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] - _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport - _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[VideoIntelligenceServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): - """Service that implements Google Cloud Video Intelligence API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "videointelligence.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VideoIntelligenceServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, VideoIntelligenceServiceTransport): - # transport is a VideoIntelligenceServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def annotate_video(self, - request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (Union[google.cloud.videointelligence_v1beta2.types.AnnotateVideoRequest, dict]): - The request object. Video annotation request. - input_uri (str): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and - thus identify multiple videos. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - should be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (Sequence[google.cloud.videointelligence_v1beta2.types.Feature]): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1beta2.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a video_intelligence.AnnotateVideoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, video_intelligence.AnnotateVideoRequest): - request = video_intelligence.AnnotateVideoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features is not None: - request.features = features - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.annotate_video] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceClient", -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py deleted file mode 100644 index ef66f264..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import VideoIntelligenceServiceTransport -from .grpc import VideoIntelligenceServiceGrpcTransport -from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] -_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport - -__all__ = ( - 'VideoIntelligenceServiceTransport', - 'VideoIntelligenceServiceGrpcTransport', - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py deleted file mode 100644 index 501c4281..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/base.py +++ /dev/null @@ -1,191 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1beta2.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-videointelligence', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class VideoIntelligenceServiceTransport(abc.ABC): - """Abstract transport class for VideoIntelligenceService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'videointelligence.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.annotate_video: gapic_v1.method.wrap_method( - self.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VideoIntelligenceServiceTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py deleted file mode 100644 index 67292694..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.videointelligence_v1beta2.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO - - -class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): - """gRPC backend transport for VideoIntelligenceService. - - Service that implements Google Cloud Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - operations_pb2.Operation]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1beta2.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'VideoIntelligenceServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py deleted file mode 100644 index 9015f0bf..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/services/video_intelligence_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.videointelligence_v1beta2.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import VideoIntelligenceServiceGrpcTransport - - -class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): - """gRPC AsyncIO backend transport for VideoIntelligenceService. - - Service that implements Google Cloud Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1beta2.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py deleted file mode 100644 index 7058cf37..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/__init__.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .video_intelligence import ( - AnnotateVideoProgress, - AnnotateVideoRequest, - AnnotateVideoResponse, - Entity, - ExplicitContentAnnotation, - ExplicitContentDetectionConfig, - ExplicitContentFrame, - FaceAnnotation, - FaceDetectionConfig, - FaceFrame, - FaceSegment, - LabelAnnotation, - LabelDetectionConfig, - LabelFrame, - LabelSegment, - NormalizedBoundingBox, - ShotChangeDetectionConfig, - VideoAnnotationProgress, - VideoAnnotationResults, - VideoContext, - VideoSegment, - Feature, - LabelDetectionMode, - Likelihood, -) - -__all__ = ( - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'FaceAnnotation', - 'FaceDetectionConfig', - 'FaceFrame', - 'FaceSegment', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'NormalizedBoundingBox', - 'ShotChangeDetectionConfig', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py b/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py deleted file mode 100644 index fbb60081..00000000 --- a/owl-bot-staging/v1beta2/google/cloud/videointelligence_v1beta2/types/video_intelligence.py +++ /dev/null @@ -1,718 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.videointelligence.v1beta2', - manifest={ - 'Feature', - 'LabelDetectionMode', - 'Likelihood', - 'AnnotateVideoRequest', - 'VideoContext', - 'LabelDetectionConfig', - 'ShotChangeDetectionConfig', - 'ExplicitContentDetectionConfig', - 'FaceDetectionConfig', - 'VideoSegment', - 'LabelSegment', - 'LabelFrame', - 'Entity', - 'LabelAnnotation', - 'ExplicitContentFrame', - 'ExplicitContentAnnotation', - 'NormalizedBoundingBox', - 'FaceSegment', - 'FaceFrame', - 'FaceAnnotation', - 'VideoAnnotationResults', - 'AnnotateVideoResponse', - 'VideoAnnotationProgress', - 'AnnotateVideoProgress', - }, -) - - -class Feature(proto.Enum): - r"""Video annotation feature.""" - FEATURE_UNSPECIFIED = 0 - LABEL_DETECTION = 1 - SHOT_CHANGE_DETECTION = 2 - EXPLICIT_CONTENT_DETECTION = 3 - FACE_DETECTION = 4 - - -class LabelDetectionMode(proto.Enum): - r"""Label detection mode.""" - LABEL_DETECTION_MODE_UNSPECIFIED = 0 - SHOT_MODE = 1 - FRAME_MODE = 2 - SHOT_AND_FRAME_MODE = 3 - - -class Likelihood(proto.Enum): - r"""Bucketized representation of likelihood.""" - LIKELIHOOD_UNSPECIFIED = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class AnnotateVideoRequest(proto.Message): - r"""Video annotation request. - - Attributes: - input_uri (str): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and thus - identify multiple videos. Supported wildcards: '*' to match - 0 or more characters; '?' to match 1 character. If unset, - the input video should be embedded in the request as - ``input_content``. If set, ``input_content`` should be - unset. - input_content (bytes): - The video data bytes. If unset, the input video(s) should be - specified via ``input_uri``. If set, ``input_uri`` should be - unset. - features (Sequence[google.cloud.videointelligence_v1beta2.types.Feature]): - Required. Requested video annotation - features. - video_context (google.cloud.videointelligence_v1beta2.types.VideoContext): - Additional video context and/or feature- - pecific parameters. - output_uri (str): - Optional. Location where the output (in JSON format) should - be stored. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - location_id (str): - Optional. Cloud region where annotation should take place. - Supported cloud regions: ``us-east1``, ``us-west1``, - ``europe-west1``, ``asia-east1``. If no region is specified, - a region will be determined based on video file location. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - input_content = proto.Field( - proto.BYTES, - number=6, - ) - features = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Feature', - ) - video_context = proto.Field( - proto.MESSAGE, - number=3, - message='VideoContext', - ) - output_uri = proto.Field( - proto.STRING, - number=4, - ) - location_id = proto.Field( - proto.STRING, - number=5, - ) - - -class VideoContext(proto.Message): - r"""Video context and/or feature-specific parameters. - - Attributes: - segments (Sequence[google.cloud.videointelligence_v1beta2.types.VideoSegment]): - Video segments to annotate. The segments may - overlap and are not required to be contiguous or - span the whole video. If unspecified, each video - is treated as a single segment. - label_detection_config (google.cloud.videointelligence_v1beta2.types.LabelDetectionConfig): - Config for LABEL_DETECTION. - shot_change_detection_config (google.cloud.videointelligence_v1beta2.types.ShotChangeDetectionConfig): - Config for SHOT_CHANGE_DETECTION. - explicit_content_detection_config (google.cloud.videointelligence_v1beta2.types.ExplicitContentDetectionConfig): - Config for EXPLICIT_CONTENT_DETECTION. - face_detection_config (google.cloud.videointelligence_v1beta2.types.FaceDetectionConfig): - Config for FACE_DETECTION. - """ - - segments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - label_detection_config = proto.Field( - proto.MESSAGE, - number=2, - message='LabelDetectionConfig', - ) - shot_change_detection_config = proto.Field( - proto.MESSAGE, - number=3, - message='ShotChangeDetectionConfig', - ) - explicit_content_detection_config = proto.Field( - proto.MESSAGE, - number=4, - message='ExplicitContentDetectionConfig', - ) - face_detection_config = proto.Field( - proto.MESSAGE, - number=5, - message='FaceDetectionConfig', - ) - - -class LabelDetectionConfig(proto.Message): - r"""Config for LABEL_DETECTION. - - Attributes: - label_detection_mode (google.cloud.videointelligence_v1beta2.types.LabelDetectionMode): - What labels should be detected with LABEL_DETECTION, in - addition to video-level labels or segment-level labels. If - unspecified, defaults to ``SHOT_MODE``. - stationary_camera (bool): - Whether the video has been shot from a stationary (i.e. - non-moving) camera. When set to true, might improve - detection accuracy for moving objects. Should be used with - ``SHOT_AND_FRAME_MODE`` enabled. - model (str): - Model to use for label detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - label_detection_mode = proto.Field( - proto.ENUM, - number=1, - enum='LabelDetectionMode', - ) - stationary_camera = proto.Field( - proto.BOOL, - number=2, - ) - model = proto.Field( - proto.STRING, - number=3, - ) - - -class ShotChangeDetectionConfig(proto.Message): - r"""Config for SHOT_CHANGE_DETECTION. - - Attributes: - model (str): - Model to use for shot change detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class ExplicitContentDetectionConfig(proto.Message): - r"""Config for EXPLICIT_CONTENT_DETECTION. - - Attributes: - model (str): - Model to use for explicit content detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class FaceDetectionConfig(proto.Message): - r"""Config for FACE_DETECTION. - - Attributes: - model (str): - Model to use for face detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - include_bounding_boxes (bool): - Whether bounding boxes be included in the - face annotation output. - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - include_bounding_boxes = proto.Field( - proto.BOOL, - number=2, - ) - - -class VideoSegment(proto.Message): - r"""Video segment. - - Attributes: - start_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the start of the segment - (inclusive). - end_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the end of the segment - (inclusive). - """ - - start_time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class LabelSegment(proto.Message): - r"""Video segment level annotation results for label detection. - - Attributes: - segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): - Video segment where a label was detected. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class LabelFrame(proto.Message): - r"""Video frame level annotation results for label detection. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class Entity(proto.Message): - r"""Detected entity from video analysis. - - Attributes: - entity_id (str): - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search - API `__. - description (str): - Textual description, e.g. ``Fixed-gear bicycle``. - language_code (str): - Language code for ``description`` in BCP-47 format. - """ - - entity_id = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class LabelAnnotation(proto.Message): - r"""Label annotation. - - Attributes: - entity (google.cloud.videointelligence_v1beta2.types.Entity): - Detected entity. - category_entities (Sequence[google.cloud.videointelligence_v1beta2.types.Entity]): - Common categories for the detected entity. E.g. when the - label is ``Terrier`` the category is likely ``dog``. And in - some cases there might be more than one categories e.g. - ``Terrier`` could also be a ``pet``. - segments (Sequence[google.cloud.videointelligence_v1beta2.types.LabelSegment]): - All video segments where a label was - detected. - frames (Sequence[google.cloud.videointelligence_v1beta2.types.LabelFrame]): - All video frames where a label was detected. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - category_entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Entity', - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelSegment', - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelFrame', - ) - - -class ExplicitContentFrame(proto.Message): - r"""Video frame level annotation results for explicit content. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - pornography_likelihood (google.cloud.videointelligence_v1beta2.types.Likelihood): - Likelihood of the pornography content.. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - pornography_likelihood = proto.Field( - proto.ENUM, - number=2, - enum='Likelihood', - ) - - -class ExplicitContentAnnotation(proto.Message): - r"""Explicit content annotation (based on per-frame visual - signals only). If no explicit content has been detected in a - frame, no annotations are present for that frame. - - Attributes: - frames (Sequence[google.cloud.videointelligence_v1beta2.types.ExplicitContentFrame]): - All video frames where explicit content was - detected. - """ - - frames = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExplicitContentFrame', - ) - - -class NormalizedBoundingBox(proto.Message): - r"""Normalized bounding box. The normalized vertex coordinates are - relative to the original image. Range: [0, 1]. - - Attributes: - left (float): - Left X coordinate. - top (float): - Top Y coordinate. - right (float): - Right X coordinate. - bottom (float): - Bottom Y coordinate. - """ - - left = proto.Field( - proto.FLOAT, - number=1, - ) - top = proto.Field( - proto.FLOAT, - number=2, - ) - right = proto.Field( - proto.FLOAT, - number=3, - ) - bottom = proto.Field( - proto.FLOAT, - number=4, - ) - - -class FaceSegment(proto.Message): - r"""Video segment level annotation results for face detection. - - Attributes: - segment (google.cloud.videointelligence_v1beta2.types.VideoSegment): - Video segment where a face was detected. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - - -class FaceFrame(proto.Message): - r"""Video frame level annotation results for face detection. - - Attributes: - normalized_bounding_boxes (Sequence[google.cloud.videointelligence_v1beta2.types.NormalizedBoundingBox]): - Normalized Bounding boxes in a frame. - There can be more than one boxes if the same - face is detected in multiple locations within - the current frame. - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - """ - - normalized_bounding_boxes = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NormalizedBoundingBox', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class FaceAnnotation(proto.Message): - r"""Face annotation. - - Attributes: - thumbnail (bytes): - Thumbnail of a representative face view (in - JPEG format). - segments (Sequence[google.cloud.videointelligence_v1beta2.types.FaceSegment]): - All video segments where a face was detected. - frames (Sequence[google.cloud.videointelligence_v1beta2.types.FaceFrame]): - All video frames where a face was detected. - """ - - thumbnail = proto.Field( - proto.BYTES, - number=1, - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='FaceSegment', - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='FaceFrame', - ) - - -class VideoAnnotationResults(proto.Message): - r"""Annotation results for a single video. - - Attributes: - input_uri (str): - Video file location in `Google Cloud - Storage `__. - segment_label_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.LabelAnnotation]): - Label annotations on video level or user - specified segment level. There is exactly one - element for each unique label. - shot_label_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.LabelAnnotation]): - Label annotations on shot level. - There is exactly one element for each unique - label. - frame_label_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.LabelAnnotation]): - Label annotations on frame level. - There is exactly one element for each unique - label. - face_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.FaceAnnotation]): - Face annotations. There is exactly one - element for each unique face. - shot_annotations (Sequence[google.cloud.videointelligence_v1beta2.types.VideoSegment]): - Shot annotations. Each shot is represented as - a video segment. - explicit_annotation (google.cloud.videointelligence_v1beta2.types.ExplicitContentAnnotation): - Explicit content annotation. - error (google.rpc.status_pb2.Status): - If set, indicates an error. Note that for a single - ``AnnotateVideoRequest`` some videos may succeed and some - may fail. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - segment_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='LabelAnnotation', - ) - shot_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelAnnotation', - ) - frame_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelAnnotation', - ) - face_annotations = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='FaceAnnotation', - ) - shot_annotations = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='VideoSegment', - ) - explicit_annotation = proto.Field( - proto.MESSAGE, - number=7, - message='ExplicitContentAnnotation', - ) - error = proto.Field( - proto.MESSAGE, - number=9, - message=status_pb2.Status, - ) - - -class AnnotateVideoResponse(proto.Message): - r"""Video annotation response. Included in the ``response`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_results (Sequence[google.cloud.videointelligence_v1beta2.types.VideoAnnotationResults]): - Annotation results for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationResults', - ) - - -class VideoAnnotationProgress(proto.Message): - r"""Annotation progress for a single video. - - Attributes: - input_uri (str): - Video file location in `Google Cloud - Storage `__. - progress_percent (int): - Approximate percentage processed thus far. - Guaranteed to be 100 when fully processed. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the request was received. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Time of the most recent update. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - progress_percent = proto.Field( - proto.INT32, - number=2, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class AnnotateVideoProgress(proto.Message): - r"""Video annotation progress. Included in the ``metadata`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_progress (Sequence[google.cloud.videointelligence_v1beta2.types.VideoAnnotationProgress]): - Progress metadata for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_progress = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationProgress', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta2/mypy.ini b/owl-bot-staging/v1beta2/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1beta2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1beta2/noxfile.py b/owl-bot-staging/v1beta2/noxfile.py deleted file mode 100644 index 45c1942e..00000000 --- a/owl-bot-staging/v1beta2/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/videointelligence_v1beta2/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py b/owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py deleted file mode 100644 index 7c1a29e9..00000000 --- a/owl-bot-staging/v1beta2/scripts/fixup_videointelligence_v1beta2_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class videointelligenceCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=videointelligenceCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the videointelligence client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1beta2/setup.py b/owl-bot-staging/v1beta2/setup.py deleted file mode 100644 index 87b7ba3d..00000000 --- a/owl-bot-staging/v1beta2/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-videointelligence', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1beta2/tests/__init__.py b/owl-bot-staging/v1beta2/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/__init__.py b/owl-bot-staging/v1beta2/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py b/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py b/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py deleted file mode 100644 index 3f88d4f3..00000000 --- a/owl-bot-staging/v1beta2/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py +++ /dev/null @@ -1,1177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.videointelligence_v1beta2.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient -from google.cloud.videointelligence_v1beta2.services.video_intelligence_service import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1beta2.services.video_intelligence_service import transports -from google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.videointelligence_v1beta2.types import video_intelligence -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_client_get_transport_class(): - transport = VideoIntelligenceServiceClient.get_transport_class() - available_transports = [ - transports.VideoIntelligenceServiceGrpcTransport, - ] - assert transport in available_transports - - transport = VideoIntelligenceServiceClient.get_transport_class("grpc") - assert transport == transports.VideoIntelligenceServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_video_intelligence_service_client_client_options_from_dict(): - with mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VideoIntelligenceServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_annotate_video_from_dict(): - test_annotate_video(request_type=dict) - - -def test_annotate_video_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - client.annotate_video() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - -@pytest.mark.asyncio -async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_annotate_video_async_from_dict(): - await test_annotate_video_async(request_type=dict) - - -def test_annotate_video_flattened(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -def test_annotate_video_flattened_error(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_error_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VideoIntelligenceServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VideoIntelligenceServiceGrpcTransport, - ) - -def test_video_intelligence_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_video_intelligence_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'annotate_video', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_video_intelligence_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1beta2.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "videointelligence.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="videointelligence.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_video_intelligence_service_host_no_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_host_with_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:8000' - -def test_video_intelligence_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_video_intelligence_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_video_intelligence_service_grpc_lro_client(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_video_intelligence_service_grpc_lro_async_client(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = VideoIntelligenceServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = VideoIntelligenceServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VideoIntelligenceServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = VideoIntelligenceServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = VideoIntelligenceServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = VideoIntelligenceServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = VideoIntelligenceServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = VideoIntelligenceServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = VideoIntelligenceServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc deleted file mode 100644 index 45c608f8..00000000 --- a/owl-bot-staging/v1p1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/videointelligence/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p1beta1/MANIFEST.in b/owl-bot-staging/v1p1beta1/MANIFEST.in deleted file mode 100644 index 93a795ab..00000000 --- a/owl-bot-staging/v1p1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/videointelligence *.py -recursive-include google/cloud/videointelligence_v1p1beta1 *.py diff --git a/owl-bot-staging/v1p1beta1/README.rst b/owl-bot-staging/v1p1beta1/README.rst deleted file mode 100644 index bedc3680..00000000 --- a/owl-bot-staging/v1p1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Videointelligence API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Videointelligence API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1p1beta1/docs/conf.py b/owl-bot-staging/v1p1beta1/docs/conf.py deleted file mode 100644 index 7a82f64b..00000000 --- a/owl-bot-staging/v1p1beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-videointelligence documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-videointelligence" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-videointelligence-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-videointelligence.tex", - u"google-cloud-videointelligence Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-videointelligence", - u"Google Cloud Videointelligence Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-videointelligence", - u"google-cloud-videointelligence Documentation", - author, - "google-cloud-videointelligence", - "GAPIC library for Google Cloud Videointelligence API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1p1beta1/docs/index.rst b/owl-bot-staging/v1p1beta1/docs/index.rst deleted file mode 100644 index 30457695..00000000 --- a/owl-bot-staging/v1p1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - videointelligence_v1p1beta1/services - videointelligence_v1p1beta1/types diff --git a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst deleted file mode 100644 index a26a19fe..00000000 --- a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Videointelligence v1p1beta1 API -========================================================= -.. toctree:: - :maxdepth: 2 - - video_intelligence_service diff --git a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst deleted file mode 100644 index 2aa52bbf..00000000 --- a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Videointelligence v1p1beta1 API -====================================================== - -.. automodule:: google.cloud.videointelligence_v1p1beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst b/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst deleted file mode 100644 index 423a835c..00000000 --- a/owl-bot-staging/v1p1beta1/docs/videointelligence_v1p1beta1/video_intelligence_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -VideoIntelligenceService ------------------------------------------- - -.. automodule:: google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py deleted file mode 100644 index 1e443c3a..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/__init__.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.client import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient - -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import AnnotateVideoProgress -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import AnnotateVideoRequest -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import AnnotateVideoResponse -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import Entity -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ExplicitContentAnnotation -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ExplicitContentDetectionConfig -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ExplicitContentFrame -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelAnnotation -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelDetectionConfig -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelFrame -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelSegment -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import ShotChangeDetectionConfig -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechContext -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechRecognitionAlternative -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechTranscription -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import SpeechTranscriptionConfig -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoAnnotationProgress -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoAnnotationResults -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoContext -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import VideoSegment -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import WordInfo -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import Feature -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import LabelDetectionMode -from google.cloud.videointelligence_v1p1beta1.types.video_intelligence import Likelihood - -__all__ = ('VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'ShotChangeDetectionConfig', - 'SpeechContext', - 'SpeechRecognitionAlternative', - 'SpeechTranscription', - 'SpeechTranscriptionConfig', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'WordInfo', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py deleted file mode 100644 index 77c1f395..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.video_intelligence_service import VideoIntelligenceServiceClient -from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient - -from .types.video_intelligence import AnnotateVideoProgress -from .types.video_intelligence import AnnotateVideoRequest -from .types.video_intelligence import AnnotateVideoResponse -from .types.video_intelligence import Entity -from .types.video_intelligence import ExplicitContentAnnotation -from .types.video_intelligence import ExplicitContentDetectionConfig -from .types.video_intelligence import ExplicitContentFrame -from .types.video_intelligence import LabelAnnotation -from .types.video_intelligence import LabelDetectionConfig -from .types.video_intelligence import LabelFrame -from .types.video_intelligence import LabelSegment -from .types.video_intelligence import ShotChangeDetectionConfig -from .types.video_intelligence import SpeechContext -from .types.video_intelligence import SpeechRecognitionAlternative -from .types.video_intelligence import SpeechTranscription -from .types.video_intelligence import SpeechTranscriptionConfig -from .types.video_intelligence import VideoAnnotationProgress -from .types.video_intelligence import VideoAnnotationResults -from .types.video_intelligence import VideoContext -from .types.video_intelligence import VideoSegment -from .types.video_intelligence import WordInfo -from .types.video_intelligence import Feature -from .types.video_intelligence import LabelDetectionMode -from .types.video_intelligence import Likelihood - -__all__ = ( - 'VideoIntelligenceServiceAsyncClient', -'AnnotateVideoProgress', -'AnnotateVideoRequest', -'AnnotateVideoResponse', -'Entity', -'ExplicitContentAnnotation', -'ExplicitContentDetectionConfig', -'ExplicitContentFrame', -'Feature', -'LabelAnnotation', -'LabelDetectionConfig', -'LabelDetectionMode', -'LabelFrame', -'LabelSegment', -'Likelihood', -'ShotChangeDetectionConfig', -'SpeechContext', -'SpeechRecognitionAlternative', -'SpeechTranscription', -'SpeechTranscriptionConfig', -'VideoAnnotationProgress', -'VideoAnnotationResults', -'VideoContext', -'VideoIntelligenceServiceClient', -'VideoSegment', -'WordInfo', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json deleted file mode 100644 index 6af0aca3..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/gapic_metadata.json +++ /dev/null @@ -1,33 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.videointelligence_v1p1beta1", - "protoPackage": "google.cloud.videointelligence.v1p1beta1", - "schema": "1.0", - "services": { - "VideoIntelligenceService": { - "clients": { - "grpc": { - "libraryClient": "VideoIntelligenceServiceClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VideoIntelligenceServiceAsyncClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py deleted file mode 100644 index 4094cd26..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import VideoIntelligenceServiceClient -from .async_client import VideoIntelligenceServiceAsyncClient - -__all__ = ( - 'VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py deleted file mode 100644 index 8ad1215a..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/async_client.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1p1beta1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport -from .client import VideoIntelligenceServiceClient - - -class VideoIntelligenceServiceAsyncClient: - """Service that implements Google Cloud Video Intelligence API.""" - - _client: VideoIntelligenceServiceClient - - DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) - common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) - parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) - common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) - parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = VideoIntelligenceServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def annotate_video(self, - request: video_intelligence.AnnotateVideoRequest = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (:class:`google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoRequest`): - The request object. Video annotation request. - input_uri (:class:`str`): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and - thus identify multiple videos. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - should be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (:class:`Sequence[google.cloud.videointelligence_v1p1beta1.types.Feature]`): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = video_intelligence.AnnotateVideoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features: - request.features.extend(features) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py deleted file mode 100644 index 8012f685..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/client.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1p1beta1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VideoIntelligenceServiceGrpcTransport -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -class VideoIntelligenceServiceClientMeta(type): - """Metaclass for the VideoIntelligenceService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] - _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport - _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[VideoIntelligenceServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): - """Service that implements Google Cloud Video Intelligence API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "videointelligence.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VideoIntelligenceServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, VideoIntelligenceServiceTransport): - # transport is a VideoIntelligenceServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def annotate_video(self, - request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (Union[google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoRequest, dict]): - The request object. Video annotation request. - input_uri (str): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and - thus identify multiple videos. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - should be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (Sequence[google.cloud.videointelligence_v1p1beta1.types.Feature]): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1p1beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a video_intelligence.AnnotateVideoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, video_intelligence.AnnotateVideoRequest): - request = video_intelligence.AnnotateVideoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features is not None: - request.features = features - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.annotate_video] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceClient", -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py deleted file mode 100644 index ef66f264..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import VideoIntelligenceServiceTransport -from .grpc import VideoIntelligenceServiceGrpcTransport -from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] -_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport - -__all__ = ( - 'VideoIntelligenceServiceTransport', - 'VideoIntelligenceServiceGrpcTransport', - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py deleted file mode 100644 index 69f19f4e..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/base.py +++ /dev/null @@ -1,191 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1p1beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-videointelligence', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class VideoIntelligenceServiceTransport(abc.ABC): - """Abstract transport class for VideoIntelligenceService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'videointelligence.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.annotate_video: gapic_v1.method.wrap_method( - self.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VideoIntelligenceServiceTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py deleted file mode 100644 index 621e0427..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.videointelligence_v1p1beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO - - -class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): - """gRPC backend transport for VideoIntelligenceService. - - Service that implements Google Cloud Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - operations_pb2.Operation]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'VideoIntelligenceServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py deleted file mode 100644 index d9842db5..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/services/video_intelligence_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.videointelligence_v1p1beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import VideoIntelligenceServiceGrpcTransport - - -class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): - """gRPC AsyncIO backend transport for VideoIntelligenceService. - - Service that implements Google Cloud Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py deleted file mode 100644 index 4eba1b6f..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/__init__.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .video_intelligence import ( - AnnotateVideoProgress, - AnnotateVideoRequest, - AnnotateVideoResponse, - Entity, - ExplicitContentAnnotation, - ExplicitContentDetectionConfig, - ExplicitContentFrame, - LabelAnnotation, - LabelDetectionConfig, - LabelFrame, - LabelSegment, - ShotChangeDetectionConfig, - SpeechContext, - SpeechRecognitionAlternative, - SpeechTranscription, - SpeechTranscriptionConfig, - VideoAnnotationProgress, - VideoAnnotationResults, - VideoContext, - VideoSegment, - WordInfo, - Feature, - LabelDetectionMode, - Likelihood, -) - -__all__ = ( - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'ShotChangeDetectionConfig', - 'SpeechContext', - 'SpeechRecognitionAlternative', - 'SpeechTranscription', - 'SpeechTranscriptionConfig', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'WordInfo', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py b/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py deleted file mode 100644 index 7dc6af1b..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/videointelligence_v1p1beta1/types/video_intelligence.py +++ /dev/null @@ -1,779 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.videointelligence.v1p1beta1', - manifest={ - 'Feature', - 'LabelDetectionMode', - 'Likelihood', - 'AnnotateVideoRequest', - 'VideoContext', - 'LabelDetectionConfig', - 'ShotChangeDetectionConfig', - 'ExplicitContentDetectionConfig', - 'VideoSegment', - 'LabelSegment', - 'LabelFrame', - 'Entity', - 'LabelAnnotation', - 'ExplicitContentFrame', - 'ExplicitContentAnnotation', - 'VideoAnnotationResults', - 'AnnotateVideoResponse', - 'VideoAnnotationProgress', - 'AnnotateVideoProgress', - 'SpeechTranscriptionConfig', - 'SpeechContext', - 'SpeechTranscription', - 'SpeechRecognitionAlternative', - 'WordInfo', - }, -) - - -class Feature(proto.Enum): - r"""Video annotation feature.""" - FEATURE_UNSPECIFIED = 0 - LABEL_DETECTION = 1 - SHOT_CHANGE_DETECTION = 2 - EXPLICIT_CONTENT_DETECTION = 3 - SPEECH_TRANSCRIPTION = 6 - - -class LabelDetectionMode(proto.Enum): - r"""Label detection mode.""" - LABEL_DETECTION_MODE_UNSPECIFIED = 0 - SHOT_MODE = 1 - FRAME_MODE = 2 - SHOT_AND_FRAME_MODE = 3 - - -class Likelihood(proto.Enum): - r"""Bucketized representation of likelihood.""" - LIKELIHOOD_UNSPECIFIED = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class AnnotateVideoRequest(proto.Message): - r"""Video annotation request. - - Attributes: - input_uri (str): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and thus - identify multiple videos. Supported wildcards: '*' to match - 0 or more characters; '?' to match 1 character. If unset, - the input video should be embedded in the request as - ``input_content``. If set, ``input_content`` should be - unset. - input_content (bytes): - The video data bytes. If unset, the input video(s) should be - specified via ``input_uri``. If set, ``input_uri`` should be - unset. - features (Sequence[google.cloud.videointelligence_v1p1beta1.types.Feature]): - Required. Requested video annotation - features. - video_context (google.cloud.videointelligence_v1p1beta1.types.VideoContext): - Additional video context and/or feature- - pecific parameters. - output_uri (str): - Optional. Location where the output (in JSON format) should - be stored. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - location_id (str): - Optional. Cloud region where annotation should take place. - Supported cloud regions: ``us-east1``, ``us-west1``, - ``europe-west1``, ``asia-east1``. If no region is specified, - a region will be determined based on video file location. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - input_content = proto.Field( - proto.BYTES, - number=6, - ) - features = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Feature', - ) - video_context = proto.Field( - proto.MESSAGE, - number=3, - message='VideoContext', - ) - output_uri = proto.Field( - proto.STRING, - number=4, - ) - location_id = proto.Field( - proto.STRING, - number=5, - ) - - -class VideoContext(proto.Message): - r"""Video context and/or feature-specific parameters. - - Attributes: - segments (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoSegment]): - Video segments to annotate. The segments may - overlap and are not required to be contiguous or - span the whole video. If unspecified, each video - is treated as a single segment. - label_detection_config (google.cloud.videointelligence_v1p1beta1.types.LabelDetectionConfig): - Config for LABEL_DETECTION. - shot_change_detection_config (google.cloud.videointelligence_v1p1beta1.types.ShotChangeDetectionConfig): - Config for SHOT_CHANGE_DETECTION. - explicit_content_detection_config (google.cloud.videointelligence_v1p1beta1.types.ExplicitContentDetectionConfig): - Config for EXPLICIT_CONTENT_DETECTION. - speech_transcription_config (google.cloud.videointelligence_v1p1beta1.types.SpeechTranscriptionConfig): - Config for SPEECH_TRANSCRIPTION. - """ - - segments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - label_detection_config = proto.Field( - proto.MESSAGE, - number=2, - message='LabelDetectionConfig', - ) - shot_change_detection_config = proto.Field( - proto.MESSAGE, - number=3, - message='ShotChangeDetectionConfig', - ) - explicit_content_detection_config = proto.Field( - proto.MESSAGE, - number=4, - message='ExplicitContentDetectionConfig', - ) - speech_transcription_config = proto.Field( - proto.MESSAGE, - number=6, - message='SpeechTranscriptionConfig', - ) - - -class LabelDetectionConfig(proto.Message): - r"""Config for LABEL_DETECTION. - - Attributes: - label_detection_mode (google.cloud.videointelligence_v1p1beta1.types.LabelDetectionMode): - What labels should be detected with LABEL_DETECTION, in - addition to video-level labels or segment-level labels. If - unspecified, defaults to ``SHOT_MODE``. - stationary_camera (bool): - Whether the video has been shot from a stationary (i.e. - non-moving) camera. When set to true, might improve - detection accuracy for moving objects. Should be used with - ``SHOT_AND_FRAME_MODE`` enabled. - model (str): - Model to use for label detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - label_detection_mode = proto.Field( - proto.ENUM, - number=1, - enum='LabelDetectionMode', - ) - stationary_camera = proto.Field( - proto.BOOL, - number=2, - ) - model = proto.Field( - proto.STRING, - number=3, - ) - - -class ShotChangeDetectionConfig(proto.Message): - r"""Config for SHOT_CHANGE_DETECTION. - - Attributes: - model (str): - Model to use for shot change detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class ExplicitContentDetectionConfig(proto.Message): - r"""Config for EXPLICIT_CONTENT_DETECTION. - - Attributes: - model (str): - Model to use for explicit content detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class VideoSegment(proto.Message): - r"""Video segment. - - Attributes: - start_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the start of the segment - (inclusive). - end_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the end of the segment - (inclusive). - """ - - start_time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class LabelSegment(proto.Message): - r"""Video segment level annotation results for label detection. - - Attributes: - segment (google.cloud.videointelligence_v1p1beta1.types.VideoSegment): - Video segment where a label was detected. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class LabelFrame(proto.Message): - r"""Video frame level annotation results for label detection. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class Entity(proto.Message): - r"""Detected entity from video analysis. - - Attributes: - entity_id (str): - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search - API `__. - description (str): - Textual description, e.g. ``Fixed-gear bicycle``. - language_code (str): - Language code for ``description`` in BCP-47 format. - """ - - entity_id = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class LabelAnnotation(proto.Message): - r"""Label annotation. - - Attributes: - entity (google.cloud.videointelligence_v1p1beta1.types.Entity): - Detected entity. - category_entities (Sequence[google.cloud.videointelligence_v1p1beta1.types.Entity]): - Common categories for the detected entity. E.g. when the - label is ``Terrier`` the category is likely ``dog``. And in - some cases there might be more than one categories e.g. - ``Terrier`` could also be a ``pet``. - segments (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelSegment]): - All video segments where a label was - detected. - frames (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelFrame]): - All video frames where a label was detected. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - category_entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Entity', - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelSegment', - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelFrame', - ) - - -class ExplicitContentFrame(proto.Message): - r"""Video frame level annotation results for explicit content. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - pornography_likelihood (google.cloud.videointelligence_v1p1beta1.types.Likelihood): - Likelihood of the pornography content.. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - pornography_likelihood = proto.Field( - proto.ENUM, - number=2, - enum='Likelihood', - ) - - -class ExplicitContentAnnotation(proto.Message): - r"""Explicit content annotation (based on per-frame visual - signals only). If no explicit content has been detected in a - frame, no annotations are present for that frame. - - Attributes: - frames (Sequence[google.cloud.videointelligence_v1p1beta1.types.ExplicitContentFrame]): - All video frames where explicit content was - detected. - """ - - frames = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExplicitContentFrame', - ) - - -class VideoAnnotationResults(proto.Message): - r"""Annotation results for a single video. - - Attributes: - input_uri (str): - Output only. Video file location in `Google Cloud - Storage `__. - segment_label_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelAnnotation]): - Label annotations on video level or user - specified segment level. There is exactly one - element for each unique label. - shot_label_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelAnnotation]): - Label annotations on shot level. - There is exactly one element for each unique - label. - frame_label_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.LabelAnnotation]): - Label annotations on frame level. - There is exactly one element for each unique - label. - shot_annotations (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoSegment]): - Shot annotations. Each shot is represented as - a video segment. - explicit_annotation (google.cloud.videointelligence_v1p1beta1.types.ExplicitContentAnnotation): - Explicit content annotation. - speech_transcriptions (Sequence[google.cloud.videointelligence_v1p1beta1.types.SpeechTranscription]): - Speech transcription. - error (google.rpc.status_pb2.Status): - Output only. If set, indicates an error. Note that for a - single ``AnnotateVideoRequest`` some videos may succeed and - some may fail. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - segment_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='LabelAnnotation', - ) - shot_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelAnnotation', - ) - frame_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelAnnotation', - ) - shot_annotations = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='VideoSegment', - ) - explicit_annotation = proto.Field( - proto.MESSAGE, - number=7, - message='ExplicitContentAnnotation', - ) - speech_transcriptions = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='SpeechTranscription', - ) - error = proto.Field( - proto.MESSAGE, - number=9, - message=status_pb2.Status, - ) - - -class AnnotateVideoResponse(proto.Message): - r"""Video annotation response. Included in the ``response`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_results (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoAnnotationResults]): - Annotation results for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationResults', - ) - - -class VideoAnnotationProgress(proto.Message): - r"""Annotation progress for a single video. - - Attributes: - input_uri (str): - Output only. Video file location in `Google Cloud - Storage `__. - progress_percent (int): - Output only. Approximate percentage processed - thus far. Guaranteed to be 100 when fully - processed. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the request was - received. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time of the most recent update. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - progress_percent = proto.Field( - proto.INT32, - number=2, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class AnnotateVideoProgress(proto.Message): - r"""Video annotation progress. Included in the ``metadata`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_progress (Sequence[google.cloud.videointelligence_v1p1beta1.types.VideoAnnotationProgress]): - Progress metadata for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_progress = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationProgress', - ) - - -class SpeechTranscriptionConfig(proto.Message): - r"""Config for SPEECH_TRANSCRIPTION. - - Attributes: - language_code (str): - Required. *Required* The language of the supplied audio as a - `BCP-47 `__ - language tag. Example: "en-US". See `Language - Support `__ - for a list of the currently supported language codes. - max_alternatives (int): - Optional. Maximum number of recognition hypotheses to be - returned. Specifically, the maximum number of - ``SpeechRecognitionAlternative`` messages within each - ``SpeechTranscription``. The server may return fewer than - ``max_alternatives``. Valid values are ``0``-``30``. A value - of ``0`` or ``1`` will return a maximum of one. If omitted, - will return a maximum of one. - filter_profanity (bool): - Optional. If set to ``true``, the server will attempt to - filter out profanities, replacing all but the initial - character in each filtered word with asterisks, e.g. "f***". - If set to ``false`` or omitted, profanities won't be - filtered out. - speech_contexts (Sequence[google.cloud.videointelligence_v1p1beta1.types.SpeechContext]): - Optional. A means to provide context to - assist the speech recognition. - enable_automatic_punctuation (bool): - Optional. If 'true', adds punctuation to - recognition result hypotheses. This feature is - only available in select languages. Setting this - for requests in other languages has no effect at - all. The default 'false' value does not add - punctuation to result hypotheses. NOTE: "This is - currently offered as an experimental service, - complimentary to all users. In the future this - may be exclusively available as a premium - feature.". - audio_tracks (Sequence[int]): - Optional. For file formats, such as MXF or - MKV, supporting multiple audio tracks, specify - up to two tracks. Default: track 0. - """ - - language_code = proto.Field( - proto.STRING, - number=1, - ) - max_alternatives = proto.Field( - proto.INT32, - number=2, - ) - filter_profanity = proto.Field( - proto.BOOL, - number=3, - ) - speech_contexts = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SpeechContext', - ) - enable_automatic_punctuation = proto.Field( - proto.BOOL, - number=5, - ) - audio_tracks = proto.RepeatedField( - proto.INT32, - number=6, - ) - - -class SpeechContext(proto.Message): - r"""Provides "hints" to the speech recognizer to favor specific - words and phrases in the results. - - Attributes: - phrases (Sequence[str]): - Optional. A list of strings containing words and phrases - "hints" so that the speech recognition is more likely to - recognize them. This can be used to improve the accuracy for - specific words and phrases, for example, if specific - commands are typically spoken by the user. This can also be - used to add additional words to the vocabulary of the - recognizer. See `usage - limits `__. - """ - - phrases = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class SpeechTranscription(proto.Message): - r"""A speech recognition result corresponding to a portion of the - audio. - - Attributes: - alternatives (Sequence[google.cloud.videointelligence_v1p1beta1.types.SpeechRecognitionAlternative]): - May contain one or more recognition hypotheses (up to the - maximum specified in ``max_alternatives``). These - alternatives are ordered in terms of accuracy, with the top - (first) alternative being the most probable, as ranked by - the recognizer. - """ - - alternatives = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SpeechRecognitionAlternative', - ) - - -class SpeechRecognitionAlternative(proto.Message): - r"""Alternative hypotheses (a.k.a. n-best list). - - Attributes: - transcript (str): - Output only. Transcript text representing the - words that the user spoke. - confidence (float): - Output only. The confidence estimate between 0.0 and 1.0. A - higher number indicates an estimated greater likelihood that - the recognized words are correct. This field is set only for - the top alternative. This field is not guaranteed to be - accurate and users should not rely on it to be always - provided. The default of 0.0 is a sentinel value indicating - ``confidence`` was not set. - words (Sequence[google.cloud.videointelligence_v1p1beta1.types.WordInfo]): - Output only. A list of word-specific - information for each recognized word. - """ - - transcript = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - words = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='WordInfo', - ) - - -class WordInfo(proto.Message): - r"""Word-specific information for recognized words. Word information is - only included in the response when certain request parameters are - set, such as ``enable_word_time_offsets``. - - Attributes: - start_time (google.protobuf.duration_pb2.Duration): - Output only. Time offset relative to the beginning of the - audio, and corresponding to the start of the spoken word. - This field is only set if ``enable_word_time_offsets=true`` - and only in the top hypothesis. This is an experimental - feature and the accuracy of the time offset can vary. - end_time (google.protobuf.duration_pb2.Duration): - Output only. Time offset relative to the beginning of the - audio, and corresponding to the end of the spoken word. This - field is only set if ``enable_word_time_offsets=true`` and - only in the top hypothesis. This is an experimental feature - and the accuracy of the time offset can vary. - word (str): - Output only. The word corresponding to this - set of information. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - word = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/mypy.ini b/owl-bot-staging/v1p1beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1p1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p1beta1/noxfile.py b/owl-bot-staging/v1p1beta1/noxfile.py deleted file mode 100644 index 69fa0116..00000000 --- a/owl-bot-staging/v1p1beta1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/videointelligence_v1p1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py b/owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py deleted file mode 100644 index 7c1a29e9..00000000 --- a/owl-bot-staging/v1p1beta1/scripts/fixup_videointelligence_v1p1beta1_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class videointelligenceCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=videointelligenceCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the videointelligence client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1p1beta1/setup.py b/owl-bot-staging/v1p1beta1/setup.py deleted file mode 100644 index 87b7ba3d..00000000 --- a/owl-bot-staging/v1p1beta1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-videointelligence', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py deleted file mode 100644 index 485bc189..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py +++ /dev/null @@ -1,1177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient -from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service import transports -from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.videointelligence_v1p1beta1.types import video_intelligence -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_client_get_transport_class(): - transport = VideoIntelligenceServiceClient.get_transport_class() - available_transports = [ - transports.VideoIntelligenceServiceGrpcTransport, - ] - assert transport in available_transports - - transport = VideoIntelligenceServiceClient.get_transport_class("grpc") - assert transport == transports.VideoIntelligenceServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_video_intelligence_service_client_client_options_from_dict(): - with mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VideoIntelligenceServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_annotate_video_from_dict(): - test_annotate_video(request_type=dict) - - -def test_annotate_video_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - client.annotate_video() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - -@pytest.mark.asyncio -async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_annotate_video_async_from_dict(): - await test_annotate_video_async(request_type=dict) - - -def test_annotate_video_flattened(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -def test_annotate_video_flattened_error(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_error_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VideoIntelligenceServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VideoIntelligenceServiceGrpcTransport, - ) - -def test_video_intelligence_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_video_intelligence_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'annotate_video', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_video_intelligence_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "videointelligence.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="videointelligence.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_video_intelligence_service_host_no_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_host_with_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:8000' - -def test_video_intelligence_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_video_intelligence_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_video_intelligence_service_grpc_lro_client(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_video_intelligence_service_grpc_lro_async_client(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = VideoIntelligenceServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = VideoIntelligenceServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VideoIntelligenceServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = VideoIntelligenceServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = VideoIntelligenceServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = VideoIntelligenceServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = VideoIntelligenceServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = VideoIntelligenceServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = VideoIntelligenceServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1p2beta1/.coveragerc b/owl-bot-staging/v1p2beta1/.coveragerc deleted file mode 100644 index 45c608f8..00000000 --- a/owl-bot-staging/v1p2beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/videointelligence/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p2beta1/MANIFEST.in b/owl-bot-staging/v1p2beta1/MANIFEST.in deleted file mode 100644 index ad395ff2..00000000 --- a/owl-bot-staging/v1p2beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/videointelligence *.py -recursive-include google/cloud/videointelligence_v1p2beta1 *.py diff --git a/owl-bot-staging/v1p2beta1/README.rst b/owl-bot-staging/v1p2beta1/README.rst deleted file mode 100644 index bedc3680..00000000 --- a/owl-bot-staging/v1p2beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Videointelligence API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Videointelligence API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1p2beta1/docs/conf.py b/owl-bot-staging/v1p2beta1/docs/conf.py deleted file mode 100644 index 7a82f64b..00000000 --- a/owl-bot-staging/v1p2beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-videointelligence documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-videointelligence" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-videointelligence-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-videointelligence.tex", - u"google-cloud-videointelligence Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-videointelligence", - u"Google Cloud Videointelligence Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-videointelligence", - u"google-cloud-videointelligence Documentation", - author, - "google-cloud-videointelligence", - "GAPIC library for Google Cloud Videointelligence API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1p2beta1/docs/index.rst b/owl-bot-staging/v1p2beta1/docs/index.rst deleted file mode 100644 index f87fd687..00000000 --- a/owl-bot-staging/v1p2beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - videointelligence_v1p2beta1/services - videointelligence_v1p2beta1/types diff --git a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst deleted file mode 100644 index e3029604..00000000 --- a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Videointelligence v1p2beta1 API -========================================================= -.. toctree:: - :maxdepth: 2 - - video_intelligence_service diff --git a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst deleted file mode 100644 index 1825803c..00000000 --- a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Videointelligence v1p2beta1 API -====================================================== - -.. automodule:: google.cloud.videointelligence_v1p2beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst b/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst deleted file mode 100644 index 804a5442..00000000 --- a/owl-bot-staging/v1p2beta1/docs/videointelligence_v1p2beta1/video_intelligence_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -VideoIntelligenceService ------------------------------------------- - -.. automodule:: google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py deleted file mode 100644 index fa93b081..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/__init__.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.client import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient - -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import AnnotateVideoProgress -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import AnnotateVideoRequest -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import AnnotateVideoResponse -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import Entity -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ExplicitContentAnnotation -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ExplicitContentDetectionConfig -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ExplicitContentFrame -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelAnnotation -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelDetectionConfig -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelFrame -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelSegment -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import NormalizedBoundingBox -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import NormalizedBoundingPoly -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import NormalizedVertex -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ObjectTrackingAnnotation -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ObjectTrackingFrame -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import ShotChangeDetectionConfig -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextAnnotation -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextDetectionConfig -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextFrame -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import TextSegment -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoAnnotationProgress -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoAnnotationResults -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoContext -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import VideoSegment -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import Feature -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import LabelDetectionMode -from google.cloud.videointelligence_v1p2beta1.types.video_intelligence import Likelihood - -__all__ = ('VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'NormalizedBoundingBox', - 'NormalizedBoundingPoly', - 'NormalizedVertex', - 'ObjectTrackingAnnotation', - 'ObjectTrackingFrame', - 'ShotChangeDetectionConfig', - 'TextAnnotation', - 'TextDetectionConfig', - 'TextFrame', - 'TextSegment', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py deleted file mode 100644 index 9ad8d5e5..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.video_intelligence_service import VideoIntelligenceServiceClient -from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient - -from .types.video_intelligence import AnnotateVideoProgress -from .types.video_intelligence import AnnotateVideoRequest -from .types.video_intelligence import AnnotateVideoResponse -from .types.video_intelligence import Entity -from .types.video_intelligence import ExplicitContentAnnotation -from .types.video_intelligence import ExplicitContentDetectionConfig -from .types.video_intelligence import ExplicitContentFrame -from .types.video_intelligence import LabelAnnotation -from .types.video_intelligence import LabelDetectionConfig -from .types.video_intelligence import LabelFrame -from .types.video_intelligence import LabelSegment -from .types.video_intelligence import NormalizedBoundingBox -from .types.video_intelligence import NormalizedBoundingPoly -from .types.video_intelligence import NormalizedVertex -from .types.video_intelligence import ObjectTrackingAnnotation -from .types.video_intelligence import ObjectTrackingFrame -from .types.video_intelligence import ShotChangeDetectionConfig -from .types.video_intelligence import TextAnnotation -from .types.video_intelligence import TextDetectionConfig -from .types.video_intelligence import TextFrame -from .types.video_intelligence import TextSegment -from .types.video_intelligence import VideoAnnotationProgress -from .types.video_intelligence import VideoAnnotationResults -from .types.video_intelligence import VideoContext -from .types.video_intelligence import VideoSegment -from .types.video_intelligence import Feature -from .types.video_intelligence import LabelDetectionMode -from .types.video_intelligence import Likelihood - -__all__ = ( - 'VideoIntelligenceServiceAsyncClient', -'AnnotateVideoProgress', -'AnnotateVideoRequest', -'AnnotateVideoResponse', -'Entity', -'ExplicitContentAnnotation', -'ExplicitContentDetectionConfig', -'ExplicitContentFrame', -'Feature', -'LabelAnnotation', -'LabelDetectionConfig', -'LabelDetectionMode', -'LabelFrame', -'LabelSegment', -'Likelihood', -'NormalizedBoundingBox', -'NormalizedBoundingPoly', -'NormalizedVertex', -'ObjectTrackingAnnotation', -'ObjectTrackingFrame', -'ShotChangeDetectionConfig', -'TextAnnotation', -'TextDetectionConfig', -'TextFrame', -'TextSegment', -'VideoAnnotationProgress', -'VideoAnnotationResults', -'VideoContext', -'VideoIntelligenceServiceClient', -'VideoSegment', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json deleted file mode 100644 index 3f52f8b4..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/gapic_metadata.json +++ /dev/null @@ -1,33 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.videointelligence_v1p2beta1", - "protoPackage": "google.cloud.videointelligence.v1p2beta1", - "schema": "1.0", - "services": { - "VideoIntelligenceService": { - "clients": { - "grpc": { - "libraryClient": "VideoIntelligenceServiceClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VideoIntelligenceServiceAsyncClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py deleted file mode 100644 index 4094cd26..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import VideoIntelligenceServiceClient -from .async_client import VideoIntelligenceServiceAsyncClient - -__all__ = ( - 'VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py deleted file mode 100644 index f746897b..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/async_client.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1p2beta1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport -from .client import VideoIntelligenceServiceClient - - -class VideoIntelligenceServiceAsyncClient: - """Service that implements Google Cloud Video Intelligence API.""" - - _client: VideoIntelligenceServiceClient - - DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) - common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) - parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) - common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) - parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = VideoIntelligenceServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def annotate_video(self, - request: video_intelligence.AnnotateVideoRequest = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (:class:`google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoRequest`): - The request object. Video annotation request. - input_uri (:class:`str`): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and - thus identify multiple videos. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - should be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (:class:`Sequence[google.cloud.videointelligence_v1p2beta1.types.Feature]`): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = video_intelligence.AnnotateVideoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features: - request.features.extend(features) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py deleted file mode 100644 index c03f1a30..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/client.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1p2beta1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VideoIntelligenceServiceGrpcTransport -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -class VideoIntelligenceServiceClientMeta(type): - """Metaclass for the VideoIntelligenceService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] - _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport - _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[VideoIntelligenceServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): - """Service that implements Google Cloud Video Intelligence API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "videointelligence.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VideoIntelligenceServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, VideoIntelligenceServiceTransport): - # transport is a VideoIntelligenceServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def annotate_video(self, - request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (Union[google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoRequest, dict]): - The request object. Video annotation request. - input_uri (str): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and - thus identify multiple videos. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - should be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (Sequence[google.cloud.videointelligence_v1p2beta1.types.Feature]): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1p2beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a video_intelligence.AnnotateVideoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, video_intelligence.AnnotateVideoRequest): - request = video_intelligence.AnnotateVideoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features is not None: - request.features = features - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.annotate_video] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceClient", -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py deleted file mode 100644 index ef66f264..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import VideoIntelligenceServiceTransport -from .grpc import VideoIntelligenceServiceGrpcTransport -from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] -_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport - -__all__ = ( - 'VideoIntelligenceServiceTransport', - 'VideoIntelligenceServiceGrpcTransport', - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py deleted file mode 100644 index 48f5ef11..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/base.py +++ /dev/null @@ -1,191 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1p2beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-videointelligence', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class VideoIntelligenceServiceTransport(abc.ABC): - """Abstract transport class for VideoIntelligenceService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'videointelligence.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.annotate_video: gapic_v1.method.wrap_method( - self.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VideoIntelligenceServiceTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py deleted file mode 100644 index 99811cd3..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.videointelligence_v1p2beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO - - -class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): - """gRPC backend transport for VideoIntelligenceService. - - Service that implements Google Cloud Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - operations_pb2.Operation]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'VideoIntelligenceServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py deleted file mode 100644 index da9634df..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/services/video_intelligence_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.videointelligence_v1p2beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import VideoIntelligenceServiceGrpcTransport - - -class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): - """gRPC AsyncIO backend transport for VideoIntelligenceService. - - Service that implements Google Cloud Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py deleted file mode 100644 index a3d9ea0d..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/__init__.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .video_intelligence import ( - AnnotateVideoProgress, - AnnotateVideoRequest, - AnnotateVideoResponse, - Entity, - ExplicitContentAnnotation, - ExplicitContentDetectionConfig, - ExplicitContentFrame, - LabelAnnotation, - LabelDetectionConfig, - LabelFrame, - LabelSegment, - NormalizedBoundingBox, - NormalizedBoundingPoly, - NormalizedVertex, - ObjectTrackingAnnotation, - ObjectTrackingFrame, - ShotChangeDetectionConfig, - TextAnnotation, - TextDetectionConfig, - TextFrame, - TextSegment, - VideoAnnotationProgress, - VideoAnnotationResults, - VideoContext, - VideoSegment, - Feature, - LabelDetectionMode, - Likelihood, -) - -__all__ = ( - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'NormalizedBoundingBox', - 'NormalizedBoundingPoly', - 'NormalizedVertex', - 'ObjectTrackingAnnotation', - 'ObjectTrackingFrame', - 'ShotChangeDetectionConfig', - 'TextAnnotation', - 'TextDetectionConfig', - 'TextFrame', - 'TextSegment', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py b/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py deleted file mode 100644 index 183599c2..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/videointelligence_v1p2beta1/types/video_intelligence.py +++ /dev/null @@ -1,853 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.videointelligence.v1p2beta1', - manifest={ - 'Feature', - 'LabelDetectionMode', - 'Likelihood', - 'AnnotateVideoRequest', - 'VideoContext', - 'LabelDetectionConfig', - 'ShotChangeDetectionConfig', - 'ExplicitContentDetectionConfig', - 'TextDetectionConfig', - 'VideoSegment', - 'LabelSegment', - 'LabelFrame', - 'Entity', - 'LabelAnnotation', - 'ExplicitContentFrame', - 'ExplicitContentAnnotation', - 'NormalizedBoundingBox', - 'VideoAnnotationResults', - 'AnnotateVideoResponse', - 'VideoAnnotationProgress', - 'AnnotateVideoProgress', - 'NormalizedVertex', - 'NormalizedBoundingPoly', - 'TextSegment', - 'TextFrame', - 'TextAnnotation', - 'ObjectTrackingFrame', - 'ObjectTrackingAnnotation', - }, -) - - -class Feature(proto.Enum): - r"""Video annotation feature.""" - FEATURE_UNSPECIFIED = 0 - LABEL_DETECTION = 1 - SHOT_CHANGE_DETECTION = 2 - EXPLICIT_CONTENT_DETECTION = 3 - TEXT_DETECTION = 7 - OBJECT_TRACKING = 9 - - -class LabelDetectionMode(proto.Enum): - r"""Label detection mode.""" - LABEL_DETECTION_MODE_UNSPECIFIED = 0 - SHOT_MODE = 1 - FRAME_MODE = 2 - SHOT_AND_FRAME_MODE = 3 - - -class Likelihood(proto.Enum): - r"""Bucketized representation of likelihood.""" - LIKELIHOOD_UNSPECIFIED = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class AnnotateVideoRequest(proto.Message): - r"""Video annotation request. - - Attributes: - input_uri (str): - Input video location. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - A video URI may include wildcards in ``object-id``, and thus - identify multiple videos. Supported wildcards: '*' to match - 0 or more characters; '?' to match 1 character. If unset, - the input video should be embedded in the request as - ``input_content``. If set, ``input_content`` should be - unset. - input_content (bytes): - The video data bytes. If unset, the input video(s) should be - specified via ``input_uri``. If set, ``input_uri`` should be - unset. - features (Sequence[google.cloud.videointelligence_v1p2beta1.types.Feature]): - Required. Requested video annotation - features. - video_context (google.cloud.videointelligence_v1p2beta1.types.VideoContext): - Additional video context and/or feature- - pecific parameters. - output_uri (str): - Optional. Location where the output (in JSON format) should - be stored. Currently, only `Google Cloud - Storage `__ URIs are - supported, which must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - location_id (str): - Optional. Cloud region where annotation should take place. - Supported cloud regions: ``us-east1``, ``us-west1``, - ``europe-west1``, ``asia-east1``. If no region is specified, - a region will be determined based on video file location. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - input_content = proto.Field( - proto.BYTES, - number=6, - ) - features = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Feature', - ) - video_context = proto.Field( - proto.MESSAGE, - number=3, - message='VideoContext', - ) - output_uri = proto.Field( - proto.STRING, - number=4, - ) - location_id = proto.Field( - proto.STRING, - number=5, - ) - - -class VideoContext(proto.Message): - r"""Video context and/or feature-specific parameters. - - Attributes: - segments (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoSegment]): - Video segments to annotate. The segments may - overlap and are not required to be contiguous or - span the whole video. If unspecified, each video - is treated as a single segment. - label_detection_config (google.cloud.videointelligence_v1p2beta1.types.LabelDetectionConfig): - Config for LABEL_DETECTION. - shot_change_detection_config (google.cloud.videointelligence_v1p2beta1.types.ShotChangeDetectionConfig): - Config for SHOT_CHANGE_DETECTION. - explicit_content_detection_config (google.cloud.videointelligence_v1p2beta1.types.ExplicitContentDetectionConfig): - Config for EXPLICIT_CONTENT_DETECTION. - text_detection_config (google.cloud.videointelligence_v1p2beta1.types.TextDetectionConfig): - Config for TEXT_DETECTION. - """ - - segments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - label_detection_config = proto.Field( - proto.MESSAGE, - number=2, - message='LabelDetectionConfig', - ) - shot_change_detection_config = proto.Field( - proto.MESSAGE, - number=3, - message='ShotChangeDetectionConfig', - ) - explicit_content_detection_config = proto.Field( - proto.MESSAGE, - number=4, - message='ExplicitContentDetectionConfig', - ) - text_detection_config = proto.Field( - proto.MESSAGE, - number=8, - message='TextDetectionConfig', - ) - - -class LabelDetectionConfig(proto.Message): - r"""Config for LABEL_DETECTION. - - Attributes: - label_detection_mode (google.cloud.videointelligence_v1p2beta1.types.LabelDetectionMode): - What labels should be detected with LABEL_DETECTION, in - addition to video-level labels or segment-level labels. If - unspecified, defaults to ``SHOT_MODE``. - stationary_camera (bool): - Whether the video has been shot from a stationary (i.e. - non-moving) camera. When set to true, might improve - detection accuracy for moving objects. Should be used with - ``SHOT_AND_FRAME_MODE`` enabled. - model (str): - Model to use for label detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - label_detection_mode = proto.Field( - proto.ENUM, - number=1, - enum='LabelDetectionMode', - ) - stationary_camera = proto.Field( - proto.BOOL, - number=2, - ) - model = proto.Field( - proto.STRING, - number=3, - ) - - -class ShotChangeDetectionConfig(proto.Message): - r"""Config for SHOT_CHANGE_DETECTION. - - Attributes: - model (str): - Model to use for shot change detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class ExplicitContentDetectionConfig(proto.Message): - r"""Config for EXPLICIT_CONTENT_DETECTION. - - Attributes: - model (str): - Model to use for explicit content detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class TextDetectionConfig(proto.Message): - r"""Config for TEXT_DETECTION. - - Attributes: - language_hints (Sequence[str]): - Language hint can be specified if the - language to be detected is known a priori. It - can increase the accuracy of the detection. - Language hint must be language code in BCP-47 - format. - - Automatic language detection is performed if no - hint is provided. - """ - - language_hints = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class VideoSegment(proto.Message): - r"""Video segment. - - Attributes: - start_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the start of the segment - (inclusive). - end_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the end of the segment - (inclusive). - """ - - start_time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class LabelSegment(proto.Message): - r"""Video segment level annotation results for label detection. - - Attributes: - segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): - Video segment where a label was detected. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class LabelFrame(proto.Message): - r"""Video frame level annotation results for label detection. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class Entity(proto.Message): - r"""Detected entity from video analysis. - - Attributes: - entity_id (str): - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search - API `__. - description (str): - Textual description, e.g. ``Fixed-gear bicycle``. - language_code (str): - Language code for ``description`` in BCP-47 format. - """ - - entity_id = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class LabelAnnotation(proto.Message): - r"""Label annotation. - - Attributes: - entity (google.cloud.videointelligence_v1p2beta1.types.Entity): - Detected entity. - category_entities (Sequence[google.cloud.videointelligence_v1p2beta1.types.Entity]): - Common categories for the detected entity. E.g. when the - label is ``Terrier`` the category is likely ``dog``. And in - some cases there might be more than one categories e.g. - ``Terrier`` could also be a ``pet``. - segments (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelSegment]): - All video segments where a label was - detected. - frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelFrame]): - All video frames where a label was detected. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - category_entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Entity', - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelSegment', - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelFrame', - ) - - -class ExplicitContentFrame(proto.Message): - r"""Video frame level annotation results for explicit content. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - pornography_likelihood (google.cloud.videointelligence_v1p2beta1.types.Likelihood): - Likelihood of the pornography content.. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - pornography_likelihood = proto.Field( - proto.ENUM, - number=2, - enum='Likelihood', - ) - - -class ExplicitContentAnnotation(proto.Message): - r"""Explicit content annotation (based on per-frame visual - signals only). If no explicit content has been detected in a - frame, no annotations are present for that frame. - - Attributes: - frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.ExplicitContentFrame]): - All video frames where explicit content was - detected. - """ - - frames = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExplicitContentFrame', - ) - - -class NormalizedBoundingBox(proto.Message): - r"""Normalized bounding box. The normalized vertex coordinates are - relative to the original image. Range: [0, 1]. - - Attributes: - left (float): - Left X coordinate. - top (float): - Top Y coordinate. - right (float): - Right X coordinate. - bottom (float): - Bottom Y coordinate. - """ - - left = proto.Field( - proto.FLOAT, - number=1, - ) - top = proto.Field( - proto.FLOAT, - number=2, - ) - right = proto.Field( - proto.FLOAT, - number=3, - ) - bottom = proto.Field( - proto.FLOAT, - number=4, - ) - - -class VideoAnnotationResults(proto.Message): - r"""Annotation results for a single video. - - Attributes: - input_uri (str): - Video file location in `Google Cloud - Storage `__. - segment_label_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelAnnotation]): - Label annotations on video level or user - specified segment level. There is exactly one - element for each unique label. - shot_label_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelAnnotation]): - Label annotations on shot level. - There is exactly one element for each unique - label. - frame_label_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.LabelAnnotation]): - Label annotations on frame level. - There is exactly one element for each unique - label. - shot_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoSegment]): - Shot annotations. Each shot is represented as - a video segment. - explicit_annotation (google.cloud.videointelligence_v1p2beta1.types.ExplicitContentAnnotation): - Explicit content annotation. - text_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.TextAnnotation]): - OCR text detection and tracking. - Annotations for list of detected text snippets. - Each will have list of frame information - associated with it. - object_annotations (Sequence[google.cloud.videointelligence_v1p2beta1.types.ObjectTrackingAnnotation]): - Annotations for list of objects detected and - tracked in video. - error (google.rpc.status_pb2.Status): - If set, indicates an error. Note that for a single - ``AnnotateVideoRequest`` some videos may succeed and some - may fail. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - segment_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='LabelAnnotation', - ) - shot_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelAnnotation', - ) - frame_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelAnnotation', - ) - shot_annotations = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='VideoSegment', - ) - explicit_annotation = proto.Field( - proto.MESSAGE, - number=7, - message='ExplicitContentAnnotation', - ) - text_annotations = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='TextAnnotation', - ) - object_annotations = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='ObjectTrackingAnnotation', - ) - error = proto.Field( - proto.MESSAGE, - number=9, - message=status_pb2.Status, - ) - - -class AnnotateVideoResponse(proto.Message): - r"""Video annotation response. Included in the ``response`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_results (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoAnnotationResults]): - Annotation results for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationResults', - ) - - -class VideoAnnotationProgress(proto.Message): - r"""Annotation progress for a single video. - - Attributes: - input_uri (str): - Video file location in `Google Cloud - Storage `__. - progress_percent (int): - Approximate percentage processed thus far. - Guaranteed to be 100 when fully processed. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the request was received. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Time of the most recent update. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - progress_percent = proto.Field( - proto.INT32, - number=2, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class AnnotateVideoProgress(proto.Message): - r"""Video annotation progress. Included in the ``metadata`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_progress (Sequence[google.cloud.videointelligence_v1p2beta1.types.VideoAnnotationProgress]): - Progress metadata for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_progress = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationProgress', - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate. - """ - - x = proto.Field( - proto.FLOAT, - number=1, - ) - y = proto.Field( - proto.FLOAT, - number=2, - ) - - -class NormalizedBoundingPoly(proto.Message): - r"""Normalized bounding polygon for text (that might not be aligned with - axis). Contains list of the corner points in clockwise order - starting from top-left corner. For example, for a rectangular - bounding box: When the text is horizontal it might look like: 0----1 - \| \| 3----2 - - When it's clockwise rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 - - and the vertex order will still be (0, 1, 2, 3). Note that values - can be less than 0, or greater than 1 due to trignometric - calculations for location of the box. - - Attributes: - vertices (Sequence[google.cloud.videointelligence_v1p2beta1.types.NormalizedVertex]): - Normalized vertices of the bounding polygon. - """ - - vertices = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NormalizedVertex', - ) - - -class TextSegment(proto.Message): - r"""Video segment level annotation results for text detection. - - Attributes: - segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): - Video segment where a text snippet was - detected. - confidence (float): - Confidence for the track of detected text. It - is calculated as the highest over all frames - where OCR detected text appears. - frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.TextFrame]): - Information related to the frames where OCR - detected text appears. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='TextFrame', - ) - - -class TextFrame(proto.Message): - r"""Video frame level annotation results for text annotation - (OCR). Contains information regarding timestamp and bounding box - locations for the frames containing detected OCR text snippets. - - Attributes: - rotated_bounding_box (google.cloud.videointelligence_v1p2beta1.types.NormalizedBoundingPoly): - Bounding polygon of the detected text for - this frame. - time_offset (google.protobuf.duration_pb2.Duration): - Timestamp of this frame. - """ - - rotated_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingPoly', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class TextAnnotation(proto.Message): - r"""Annotations related to one detected OCR text snippet. This - will contain the corresponding text, confidence value, and frame - level information for each detection. - - Attributes: - text (str): - The detected text. - segments (Sequence[google.cloud.videointelligence_v1p2beta1.types.TextSegment]): - All video segments where OCR detected text - appears. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TextSegment', - ) - - -class ObjectTrackingFrame(proto.Message): - r"""Video frame level annotations for object detection and - tracking. This field stores per frame location, time offset, and - confidence. - - Attributes: - normalized_bounding_box (google.cloud.videointelligence_v1p2beta1.types.NormalizedBoundingBox): - The normalized bounding box location of this - object track for the frame. - time_offset (google.protobuf.duration_pb2.Duration): - The timestamp of the frame in microseconds. - """ - - normalized_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingBox', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class ObjectTrackingAnnotation(proto.Message): - r"""Annotations corresponding to one tracked object. - - Attributes: - entity (google.cloud.videointelligence_v1p2beta1.types.Entity): - Entity to specify the object category that - this track is labeled as. - confidence (float): - Object category's labeling confidence of this - track. - frames (Sequence[google.cloud.videointelligence_v1p2beta1.types.ObjectTrackingFrame]): - Information corresponding to all frames where - this object track appears. - segment (google.cloud.videointelligence_v1p2beta1.types.VideoSegment): - Each object track corresponds to one video - segment where it appears. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ObjectTrackingFrame', - ) - segment = proto.Field( - proto.MESSAGE, - number=3, - message='VideoSegment', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p2beta1/mypy.ini b/owl-bot-staging/v1p2beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1p2beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p2beta1/noxfile.py b/owl-bot-staging/v1p2beta1/noxfile.py deleted file mode 100644 index eb91250c..00000000 --- a/owl-bot-staging/v1p2beta1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/videointelligence_v1p2beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py b/owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py deleted file mode 100644 index 7c1a29e9..00000000 --- a/owl-bot-staging/v1p2beta1/scripts/fixup_videointelligence_v1p2beta1_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class videointelligenceCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=videointelligenceCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the videointelligence client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1p2beta1/setup.py b/owl-bot-staging/v1p2beta1/setup.py deleted file mode 100644 index 87b7ba3d..00000000 --- a/owl-bot-staging/v1p2beta1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-videointelligence', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1p2beta1/tests/__init__.py b/owl-bot-staging/v1p2beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py deleted file mode 100644 index 093b38f4..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py +++ /dev/null @@ -1,1177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient -from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service import transports -from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.videointelligence_v1p2beta1.types import video_intelligence -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_client_get_transport_class(): - transport = VideoIntelligenceServiceClient.get_transport_class() - available_transports = [ - transports.VideoIntelligenceServiceGrpcTransport, - ] - assert transport in available_transports - - transport = VideoIntelligenceServiceClient.get_transport_class("grpc") - assert transport == transports.VideoIntelligenceServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_video_intelligence_service_client_client_options_from_dict(): - with mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VideoIntelligenceServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_annotate_video_from_dict(): - test_annotate_video(request_type=dict) - - -def test_annotate_video_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - client.annotate_video() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - -@pytest.mark.asyncio -async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_annotate_video_async_from_dict(): - await test_annotate_video_async(request_type=dict) - - -def test_annotate_video_flattened(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -def test_annotate_video_flattened_error(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_error_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VideoIntelligenceServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VideoIntelligenceServiceGrpcTransport, - ) - -def test_video_intelligence_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_video_intelligence_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'annotate_video', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_video_intelligence_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "videointelligence.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="videointelligence.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_video_intelligence_service_host_no_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_host_with_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:8000' - -def test_video_intelligence_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_video_intelligence_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_video_intelligence_service_grpc_lro_client(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_video_intelligence_service_grpc_lro_async_client(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = VideoIntelligenceServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = VideoIntelligenceServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VideoIntelligenceServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = VideoIntelligenceServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = VideoIntelligenceServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = VideoIntelligenceServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = VideoIntelligenceServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = VideoIntelligenceServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = VideoIntelligenceServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1p3beta1/.coveragerc b/owl-bot-staging/v1p3beta1/.coveragerc deleted file mode 100644 index 45c608f8..00000000 --- a/owl-bot-staging/v1p3beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/videointelligence/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p3beta1/MANIFEST.in b/owl-bot-staging/v1p3beta1/MANIFEST.in deleted file mode 100644 index e35640e6..00000000 --- a/owl-bot-staging/v1p3beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/videointelligence *.py -recursive-include google/cloud/videointelligence_v1p3beta1 *.py diff --git a/owl-bot-staging/v1p3beta1/README.rst b/owl-bot-staging/v1p3beta1/README.rst deleted file mode 100644 index bedc3680..00000000 --- a/owl-bot-staging/v1p3beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Videointelligence API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Videointelligence API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1p3beta1/docs/conf.py b/owl-bot-staging/v1p3beta1/docs/conf.py deleted file mode 100644 index 7a82f64b..00000000 --- a/owl-bot-staging/v1p3beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-videointelligence documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-videointelligence" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-videointelligence-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-videointelligence.tex", - u"google-cloud-videointelligence Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-videointelligence", - u"Google Cloud Videointelligence Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-videointelligence", - u"google-cloud-videointelligence Documentation", - author, - "google-cloud-videointelligence", - "GAPIC library for Google Cloud Videointelligence API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1p3beta1/docs/index.rst b/owl-bot-staging/v1p3beta1/docs/index.rst deleted file mode 100644 index 259bf4fc..00000000 --- a/owl-bot-staging/v1p3beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - videointelligence_v1p3beta1/services - videointelligence_v1p3beta1/types diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst deleted file mode 100644 index 853cb921..00000000 --- a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/services.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Videointelligence v1p3beta1 API -========================================================= -.. toctree:: - :maxdepth: 2 - - streaming_video_intelligence_service - video_intelligence_service diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst deleted file mode 100644 index 4de59243..00000000 --- a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/streaming_video_intelligence_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -StreamingVideoIntelligenceService ---------------------------------------------------- - -.. automodule:: google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst deleted file mode 100644 index 75c97809..00000000 --- a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Videointelligence v1p3beta1 API -====================================================== - -.. automodule:: google.cloud.videointelligence_v1p3beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst b/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst deleted file mode 100644 index fd06a199..00000000 --- a/owl-bot-staging/v1p3beta1/docs/videointelligence_v1p3beta1/video_intelligence_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -VideoIntelligenceService ------------------------------------------- - -.. automodule:: google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py deleted file mode 100644 index 5f45af06..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/__init__.py +++ /dev/null @@ -1,145 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.client import StreamingVideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.async_client import StreamingVideoIntelligenceServiceAsyncClient -from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.client import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient - -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import AnnotateVideoProgress -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import AnnotateVideoRequest -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import AnnotateVideoResponse -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Celebrity -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import CelebrityRecognitionAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import CelebrityTrack -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import DetectedAttribute -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import DetectedLandmark -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Entity -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ExplicitContentAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ExplicitContentDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ExplicitContentFrame -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import FaceDetectionAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import FaceDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelFrame -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelSegment -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LogoRecognitionAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import NormalizedBoundingBox -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import NormalizedBoundingPoly -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import NormalizedVertex -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ObjectTrackingAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ObjectTrackingConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ObjectTrackingFrame -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import PersonDetectionAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import PersonDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import ShotChangeDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechContext -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechRecognitionAlternative -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechTranscription -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import SpeechTranscriptionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAnnotateVideoRequest -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAnnotateVideoResponse -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAutomlActionRecognitionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAutomlClassificationConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingAutomlObjectTrackingConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingExplicitContentDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingLabelDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingObjectTrackingConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingShotChangeDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingStorageConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingVideoAnnotationResults -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingVideoConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextAnnotation -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextDetectionConfig -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextFrame -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TextSegment -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import TimestampedObject -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Track -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoAnnotationProgress -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoAnnotationResults -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoContext -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import VideoSegment -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import WordInfo -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Feature -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import LabelDetectionMode -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import Likelihood -from google.cloud.videointelligence_v1p3beta1.types.video_intelligence import StreamingFeature - -__all__ = ('StreamingVideoIntelligenceServiceClient', - 'StreamingVideoIntelligenceServiceAsyncClient', - 'VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Celebrity', - 'CelebrityRecognitionAnnotation', - 'CelebrityTrack', - 'DetectedAttribute', - 'DetectedLandmark', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'FaceDetectionAnnotation', - 'FaceDetectionConfig', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'LogoRecognitionAnnotation', - 'NormalizedBoundingBox', - 'NormalizedBoundingPoly', - 'NormalizedVertex', - 'ObjectTrackingAnnotation', - 'ObjectTrackingConfig', - 'ObjectTrackingFrame', - 'PersonDetectionAnnotation', - 'PersonDetectionConfig', - 'ShotChangeDetectionConfig', - 'SpeechContext', - 'SpeechRecognitionAlternative', - 'SpeechTranscription', - 'SpeechTranscriptionConfig', - 'StreamingAnnotateVideoRequest', - 'StreamingAnnotateVideoResponse', - 'StreamingAutomlActionRecognitionConfig', - 'StreamingAutomlClassificationConfig', - 'StreamingAutomlObjectTrackingConfig', - 'StreamingExplicitContentDetectionConfig', - 'StreamingLabelDetectionConfig', - 'StreamingObjectTrackingConfig', - 'StreamingShotChangeDetectionConfig', - 'StreamingStorageConfig', - 'StreamingVideoAnnotationResults', - 'StreamingVideoConfig', - 'TextAnnotation', - 'TextDetectionConfig', - 'TextFrame', - 'TextSegment', - 'TimestampedObject', - 'Track', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'WordInfo', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', - 'StreamingFeature', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py deleted file mode 100644 index d1c49b52..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/__init__.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceClient -from .services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceAsyncClient -from .services.video_intelligence_service import VideoIntelligenceServiceClient -from .services.video_intelligence_service import VideoIntelligenceServiceAsyncClient - -from .types.video_intelligence import AnnotateVideoProgress -from .types.video_intelligence import AnnotateVideoRequest -from .types.video_intelligence import AnnotateVideoResponse -from .types.video_intelligence import Celebrity -from .types.video_intelligence import CelebrityRecognitionAnnotation -from .types.video_intelligence import CelebrityTrack -from .types.video_intelligence import DetectedAttribute -from .types.video_intelligence import DetectedLandmark -from .types.video_intelligence import Entity -from .types.video_intelligence import ExplicitContentAnnotation -from .types.video_intelligence import ExplicitContentDetectionConfig -from .types.video_intelligence import ExplicitContentFrame -from .types.video_intelligence import FaceDetectionAnnotation -from .types.video_intelligence import FaceDetectionConfig -from .types.video_intelligence import LabelAnnotation -from .types.video_intelligence import LabelDetectionConfig -from .types.video_intelligence import LabelFrame -from .types.video_intelligence import LabelSegment -from .types.video_intelligence import LogoRecognitionAnnotation -from .types.video_intelligence import NormalizedBoundingBox -from .types.video_intelligence import NormalizedBoundingPoly -from .types.video_intelligence import NormalizedVertex -from .types.video_intelligence import ObjectTrackingAnnotation -from .types.video_intelligence import ObjectTrackingConfig -from .types.video_intelligence import ObjectTrackingFrame -from .types.video_intelligence import PersonDetectionAnnotation -from .types.video_intelligence import PersonDetectionConfig -from .types.video_intelligence import ShotChangeDetectionConfig -from .types.video_intelligence import SpeechContext -from .types.video_intelligence import SpeechRecognitionAlternative -from .types.video_intelligence import SpeechTranscription -from .types.video_intelligence import SpeechTranscriptionConfig -from .types.video_intelligence import StreamingAnnotateVideoRequest -from .types.video_intelligence import StreamingAnnotateVideoResponse -from .types.video_intelligence import StreamingAutomlActionRecognitionConfig -from .types.video_intelligence import StreamingAutomlClassificationConfig -from .types.video_intelligence import StreamingAutomlObjectTrackingConfig -from .types.video_intelligence import StreamingExplicitContentDetectionConfig -from .types.video_intelligence import StreamingLabelDetectionConfig -from .types.video_intelligence import StreamingObjectTrackingConfig -from .types.video_intelligence import StreamingShotChangeDetectionConfig -from .types.video_intelligence import StreamingStorageConfig -from .types.video_intelligence import StreamingVideoAnnotationResults -from .types.video_intelligence import StreamingVideoConfig -from .types.video_intelligence import TextAnnotation -from .types.video_intelligence import TextDetectionConfig -from .types.video_intelligence import TextFrame -from .types.video_intelligence import TextSegment -from .types.video_intelligence import TimestampedObject -from .types.video_intelligence import Track -from .types.video_intelligence import VideoAnnotationProgress -from .types.video_intelligence import VideoAnnotationResults -from .types.video_intelligence import VideoContext -from .types.video_intelligence import VideoSegment -from .types.video_intelligence import WordInfo -from .types.video_intelligence import Feature -from .types.video_intelligence import LabelDetectionMode -from .types.video_intelligence import Likelihood -from .types.video_intelligence import StreamingFeature - -__all__ = ( - 'StreamingVideoIntelligenceServiceAsyncClient', - 'VideoIntelligenceServiceAsyncClient', -'AnnotateVideoProgress', -'AnnotateVideoRequest', -'AnnotateVideoResponse', -'Celebrity', -'CelebrityRecognitionAnnotation', -'CelebrityTrack', -'DetectedAttribute', -'DetectedLandmark', -'Entity', -'ExplicitContentAnnotation', -'ExplicitContentDetectionConfig', -'ExplicitContentFrame', -'FaceDetectionAnnotation', -'FaceDetectionConfig', -'Feature', -'LabelAnnotation', -'LabelDetectionConfig', -'LabelDetectionMode', -'LabelFrame', -'LabelSegment', -'Likelihood', -'LogoRecognitionAnnotation', -'NormalizedBoundingBox', -'NormalizedBoundingPoly', -'NormalizedVertex', -'ObjectTrackingAnnotation', -'ObjectTrackingConfig', -'ObjectTrackingFrame', -'PersonDetectionAnnotation', -'PersonDetectionConfig', -'ShotChangeDetectionConfig', -'SpeechContext', -'SpeechRecognitionAlternative', -'SpeechTranscription', -'SpeechTranscriptionConfig', -'StreamingAnnotateVideoRequest', -'StreamingAnnotateVideoResponse', -'StreamingAutomlActionRecognitionConfig', -'StreamingAutomlClassificationConfig', -'StreamingAutomlObjectTrackingConfig', -'StreamingExplicitContentDetectionConfig', -'StreamingFeature', -'StreamingLabelDetectionConfig', -'StreamingObjectTrackingConfig', -'StreamingShotChangeDetectionConfig', -'StreamingStorageConfig', -'StreamingVideoAnnotationResults', -'StreamingVideoConfig', -'StreamingVideoIntelligenceServiceClient', -'TextAnnotation', -'TextDetectionConfig', -'TextFrame', -'TextSegment', -'TimestampedObject', -'Track', -'VideoAnnotationProgress', -'VideoAnnotationResults', -'VideoContext', -'VideoIntelligenceServiceClient', -'VideoSegment', -'WordInfo', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json deleted file mode 100644 index 040a74a1..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/gapic_metadata.json +++ /dev/null @@ -1,57 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.videointelligence_v1p3beta1", - "protoPackage": "google.cloud.videointelligence.v1p3beta1", - "schema": "1.0", - "services": { - "StreamingVideoIntelligenceService": { - "clients": { - "grpc": { - "libraryClient": "StreamingVideoIntelligenceServiceClient", - "rpcs": { - "StreamingAnnotateVideo": { - "methods": [ - "streaming_annotate_video" - ] - } - } - }, - "grpc-async": { - "libraryClient": "StreamingVideoIntelligenceServiceAsyncClient", - "rpcs": { - "StreamingAnnotateVideo": { - "methods": [ - "streaming_annotate_video" - ] - } - } - } - } - }, - "VideoIntelligenceService": { - "clients": { - "grpc": { - "libraryClient": "VideoIntelligenceServiceClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VideoIntelligenceServiceAsyncClient", - "rpcs": { - "AnnotateVideo": { - "methods": [ - "annotate_video" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed deleted file mode 100644 index e7fb166b..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-videointelligence package uses inline types. diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py deleted file mode 100644 index 6dbf9507..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import StreamingVideoIntelligenceServiceClient -from .async_client import StreamingVideoIntelligenceServiceAsyncClient - -__all__ = ( - 'StreamingVideoIntelligenceServiceClient', - 'StreamingVideoIntelligenceServiceAsyncClient', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py deleted file mode 100644 index 13109fd6..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/async_client.py +++ /dev/null @@ -1,224 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from google.rpc import status_pb2 # type: ignore -from .transports.base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import StreamingVideoIntelligenceServiceGrpcAsyncIOTransport -from .client import StreamingVideoIntelligenceServiceClient - - -class StreamingVideoIntelligenceServiceAsyncClient: - """Service that implements streaming Video Intelligence API.""" - - _client: StreamingVideoIntelligenceServiceClient - - DEFAULT_ENDPOINT = StreamingVideoIntelligenceServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = StreamingVideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_organization_path) - common_project_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_project_path) - parse_common_project_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_project_path) - common_location_path = staticmethod(StreamingVideoIntelligenceServiceClient.common_location_path) - parse_common_location_path = staticmethod(StreamingVideoIntelligenceServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - StreamingVideoIntelligenceServiceAsyncClient: The constructed client. - """ - return StreamingVideoIntelligenceServiceClient.from_service_account_info.__func__(StreamingVideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - StreamingVideoIntelligenceServiceAsyncClient: The constructed client. - """ - return StreamingVideoIntelligenceServiceClient.from_service_account_file.__func__(StreamingVideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> StreamingVideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - StreamingVideoIntelligenceServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(StreamingVideoIntelligenceServiceClient).get_transport_class, type(StreamingVideoIntelligenceServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, StreamingVideoIntelligenceServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the streaming video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.StreamingVideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = StreamingVideoIntelligenceServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - def streaming_annotate_video(self, - requests: AsyncIterator[video_intelligence.StreamingAnnotateVideoRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[video_intelligence.StreamingAnnotateVideoResponse]]: - r"""Performs video annotation with bidirectional - streaming: emitting results while sending video/audio - bytes. This method is only available via the gRPC API - (not REST). - - Args: - requests (AsyncIterator[`google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoRequest`]): - The request object AsyncIterator. The top-level message sent by the - client for the `StreamingAnnotateVideo` method. Multiple - `StreamingAnnotateVideoRequest` messages are sent. The - first message must only contain a `StreamingVideoConfig` - message. All subsequent messages must only contain - `input_content` data. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoResponse]: - StreamingAnnotateVideoResponse is the only message returned to the client - by StreamingAnnotateVideo. A series of zero or more - StreamingAnnotateVideoResponse messages are streamed - back to the client. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_annotate_video, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=10800.0, - ), - default_timeout=10800.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "StreamingVideoIntelligenceServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py deleted file mode 100644 index c5cc429d..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/client.py +++ /dev/null @@ -1,401 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from google.rpc import status_pb2 # type: ignore -from .transports.base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import StreamingVideoIntelligenceServiceGrpcTransport -from .transports.grpc_asyncio import StreamingVideoIntelligenceServiceGrpcAsyncIOTransport - - -class StreamingVideoIntelligenceServiceClientMeta(type): - """Metaclass for the StreamingVideoIntelligenceService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[StreamingVideoIntelligenceServiceTransport]] - _transport_registry["grpc"] = StreamingVideoIntelligenceServiceGrpcTransport - _transport_registry["grpc_asyncio"] = StreamingVideoIntelligenceServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[StreamingVideoIntelligenceServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class StreamingVideoIntelligenceServiceClient(metaclass=StreamingVideoIntelligenceServiceClientMeta): - """Service that implements streaming Video Intelligence API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "videointelligence.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - StreamingVideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - StreamingVideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> StreamingVideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - StreamingVideoIntelligenceServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, StreamingVideoIntelligenceServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the streaming video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, StreamingVideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, StreamingVideoIntelligenceServiceTransport): - # transport is a StreamingVideoIntelligenceServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def streaming_annotate_video(self, - requests: Iterator[video_intelligence.StreamingAnnotateVideoRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[video_intelligence.StreamingAnnotateVideoResponse]: - r"""Performs video annotation with bidirectional - streaming: emitting results while sending video/audio - bytes. This method is only available via the gRPC API - (not REST). - - Args: - requests (Iterator[google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoRequest]): - The request object iterator. The top-level message sent by the - client for the `StreamingAnnotateVideo` method. Multiple - `StreamingAnnotateVideoRequest` messages are sent. The - first message must only contain a `StreamingVideoConfig` - message. All subsequent messages must only contain - `input_content` data. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.cloud.videointelligence_v1p3beta1.types.StreamingAnnotateVideoResponse]: - StreamingAnnotateVideoResponse is the only message returned to the client - by StreamingAnnotateVideo. A series of zero or more - StreamingAnnotateVideoResponse messages are streamed - back to the client. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_annotate_video] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "StreamingVideoIntelligenceServiceClient", -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py deleted file mode 100644 index 90816d03..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import StreamingVideoIntelligenceServiceTransport -from .grpc import StreamingVideoIntelligenceServiceGrpcTransport -from .grpc_asyncio import StreamingVideoIntelligenceServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[StreamingVideoIntelligenceServiceTransport]] -_transport_registry['grpc'] = StreamingVideoIntelligenceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = StreamingVideoIntelligenceServiceGrpcAsyncIOTransport - -__all__ = ( - 'StreamingVideoIntelligenceServiceTransport', - 'StreamingVideoIntelligenceServiceGrpcTransport', - 'StreamingVideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py deleted file mode 100644 index 81c59e8f..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/base.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-videointelligence', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class StreamingVideoIntelligenceServiceTransport(abc.ABC): - """Abstract transport class for StreamingVideoIntelligenceService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'videointelligence.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.streaming_annotate_video: gapic_v1.method.wrap_method( - self.streaming_annotate_video, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=10800.0, - ), - default_timeout=10800.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def streaming_annotate_video(self) -> Callable[ - [video_intelligence.StreamingAnnotateVideoRequest], - Union[ - video_intelligence.StreamingAnnotateVideoResponse, - Awaitable[video_intelligence.StreamingAnnotateVideoResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'StreamingVideoIntelligenceServiceTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py deleted file mode 100644 index f189db30..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc.py +++ /dev/null @@ -1,257 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from .base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO - - -class StreamingVideoIntelligenceServiceGrpcTransport(StreamingVideoIntelligenceServiceTransport): - """gRPC backend transport for StreamingVideoIntelligenceService. - - Service that implements streaming Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def streaming_annotate_video(self) -> Callable[ - [video_intelligence.StreamingAnnotateVideoRequest], - video_intelligence.StreamingAnnotateVideoResponse]: - r"""Return a callable for the streaming annotate video method over gRPC. - - Performs video annotation with bidirectional - streaming: emitting results while sending video/audio - bytes. This method is only available via the gRPC API - (not REST). - - Returns: - Callable[[~.StreamingAnnotateVideoRequest], - ~.StreamingAnnotateVideoResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'streaming_annotate_video' not in self._stubs: - self._stubs['streaming_annotate_video'] = self.grpc_channel.stream_stream( - '/google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService/StreamingAnnotateVideo', - request_serializer=video_intelligence.StreamingAnnotateVideoRequest.serialize, - response_deserializer=video_intelligence.StreamingAnnotateVideoResponse.deserialize, - ) - return self._stubs['streaming_annotate_video'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'StreamingVideoIntelligenceServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py deleted file mode 100644 index 597332d5..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/streaming_video_intelligence_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from .base import StreamingVideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import StreamingVideoIntelligenceServiceGrpcTransport - - -class StreamingVideoIntelligenceServiceGrpcAsyncIOTransport(StreamingVideoIntelligenceServiceTransport): - """gRPC AsyncIO backend transport for StreamingVideoIntelligenceService. - - Service that implements streaming Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def streaming_annotate_video(self) -> Callable[ - [video_intelligence.StreamingAnnotateVideoRequest], - Awaitable[video_intelligence.StreamingAnnotateVideoResponse]]: - r"""Return a callable for the streaming annotate video method over gRPC. - - Performs video annotation with bidirectional - streaming: emitting results while sending video/audio - bytes. This method is only available via the gRPC API - (not REST). - - Returns: - Callable[[~.StreamingAnnotateVideoRequest], - Awaitable[~.StreamingAnnotateVideoResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'streaming_annotate_video' not in self._stubs: - self._stubs['streaming_annotate_video'] = self.grpc_channel.stream_stream( - '/google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService/StreamingAnnotateVideo', - request_serializer=video_intelligence.StreamingAnnotateVideoRequest.serialize, - response_deserializer=video_intelligence.StreamingAnnotateVideoResponse.deserialize, - ) - return self._stubs['streaming_annotate_video'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'StreamingVideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py deleted file mode 100644 index 4094cd26..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import VideoIntelligenceServiceClient -from .async_client import VideoIntelligenceServiceAsyncClient - -__all__ = ( - 'VideoIntelligenceServiceClient', - 'VideoIntelligenceServiceAsyncClient', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py deleted file mode 100644 index 5c537982..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/async_client.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport -from .client import VideoIntelligenceServiceClient - - -class VideoIntelligenceServiceAsyncClient: - """Service that implements the Video Intelligence API.""" - - _client: VideoIntelligenceServiceClient - - DEFAULT_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VideoIntelligenceServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VideoIntelligenceServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VideoIntelligenceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(VideoIntelligenceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(VideoIntelligenceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(VideoIntelligenceServiceClient.parse_common_organization_path) - common_project_path = staticmethod(VideoIntelligenceServiceClient.common_project_path) - parse_common_project_path = staticmethod(VideoIntelligenceServiceClient.parse_common_project_path) - common_location_path = staticmethod(VideoIntelligenceServiceClient.common_location_path) - parse_common_location_path = staticmethod(VideoIntelligenceServiceClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_info.__func__(VideoIntelligenceServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceAsyncClient: The constructed client. - """ - return VideoIntelligenceServiceClient.from_service_account_file.__func__(VideoIntelligenceServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(VideoIntelligenceServiceClient).get_transport_class, type(VideoIntelligenceServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VideoIntelligenceServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = VideoIntelligenceServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def annotate_video(self, - request: video_intelligence.AnnotateVideoRequest = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (:class:`google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoRequest`): - The request object. Video annotation request. - input_uri (:class:`str`): - Input video location. Currently, only `Cloud - Storage `__ URIs are - supported. URIs must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - To identify multiple videos, a video URI may include - wildcards in the ``object-id``. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - must be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (:class:`Sequence[google.cloud.videointelligence_v1p3beta1.types.Feature]`): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = video_intelligence.AnnotateVideoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features: - request.features.extend(features) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py deleted file mode 100644 index fc127d7c..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/client.py +++ /dev/null @@ -1,455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from .transports.base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VideoIntelligenceServiceGrpcTransport -from .transports.grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -class VideoIntelligenceServiceClientMeta(type): - """Metaclass for the VideoIntelligenceService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] - _transport_registry["grpc"] = VideoIntelligenceServiceGrpcTransport - _transport_registry["grpc_asyncio"] = VideoIntelligenceServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[VideoIntelligenceServiceTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VideoIntelligenceServiceClient(metaclass=VideoIntelligenceServiceClientMeta): - """Service that implements the Video Intelligence API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "videointelligence.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VideoIntelligenceServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VideoIntelligenceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VideoIntelligenceServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VideoIntelligenceServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the video intelligence service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, VideoIntelligenceServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, VideoIntelligenceServiceTransport): - # transport is a VideoIntelligenceServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - ) - - def annotate_video(self, - request: Union[video_intelligence.AnnotateVideoRequest, dict] = None, - *, - input_uri: str = None, - features: Sequence[video_intelligence.Feature] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Args: - request (Union[google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoRequest, dict]): - The request object. Video annotation request. - input_uri (str): - Input video location. Currently, only `Cloud - Storage `__ URIs are - supported. URIs must be specified in the following - format: ``gs://bucket-id/object-id`` (other URI formats - return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - To identify multiple videos, a video URI may include - wildcards in the ``object-id``. Supported wildcards: '*' - to match 0 or more characters; '?' to match 1 character. - If unset, the input video should be embedded in the - request as ``input_content``. If set, ``input_content`` - must be unset. - - This corresponds to the ``input_uri`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - features (Sequence[google.cloud.videointelligence_v1p3beta1.types.Feature]): - Required. Requested video annotation - features. - - This corresponds to the ``features`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.videointelligence_v1p3beta1.types.AnnotateVideoResponse` Video annotation response. Included in the response - field of the Operation returned by the GetOperation - call of the google::longrunning::Operations service. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([input_uri, features]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a video_intelligence.AnnotateVideoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, video_intelligence.AnnotateVideoRequest): - request = video_intelligence.AnnotateVideoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if input_uri is not None: - request.input_uri = input_uri - if features is not None: - request.features = features - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.annotate_video] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - video_intelligence.AnnotateVideoResponse, - metadata_type=video_intelligence.AnnotateVideoProgress, - ) - - # Done; return the response. - return response - - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-videointelligence", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VideoIntelligenceServiceClient", -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py deleted file mode 100644 index ef66f264..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import VideoIntelligenceServiceTransport -from .grpc import VideoIntelligenceServiceGrpcTransport -from .grpc_asyncio import VideoIntelligenceServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VideoIntelligenceServiceTransport]] -_transport_registry['grpc'] = VideoIntelligenceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = VideoIntelligenceServiceGrpcAsyncIOTransport - -__all__ = ( - 'VideoIntelligenceServiceTransport', - 'VideoIntelligenceServiceGrpcTransport', - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py deleted file mode 100644 index a7ad78fc..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/base.py +++ /dev/null @@ -1,191 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-videointelligence', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class VideoIntelligenceServiceTransport(abc.ABC): - """Abstract transport class for VideoIntelligenceService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'videointelligence.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.annotate_video: gapic_v1.method.wrap_method( - self.annotate_video, - default_retry=retries.Retry( -initial=1.0,maximum=120.0,multiplier=2.5, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VideoIntelligenceServiceTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py deleted file mode 100644 index 07368d0d..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO - - -class VideoIntelligenceServiceGrpcTransport(VideoIntelligenceServiceTransport): - """gRPC backend transport for VideoIntelligenceService. - - Service that implements the Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - operations_pb2.Operation]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - self.grpc_channel.close() - -__all__ = ( - 'VideoIntelligenceServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py deleted file mode 100644 index e6fa875b..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/services/video_intelligence_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,282 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from google.longrunning import operations_pb2 # type: ignore -from .base import VideoIntelligenceServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import VideoIntelligenceServiceGrpcTransport - - -class VideoIntelligenceServiceGrpcAsyncIOTransport(VideoIntelligenceServiceTransport): - """gRPC AsyncIO backend transport for VideoIntelligenceService. - - Service that implements the Video Intelligence API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'videointelligence.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def annotate_video(self) -> Callable[ - [video_intelligence.AnnotateVideoRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the annotate video method over gRPC. - - Performs asynchronous video annotation. Progress and results can - be retrieved through the ``google.longrunning.Operations`` - interface. ``Operation.metadata`` contains - ``AnnotateVideoProgress`` (progress). ``Operation.response`` - contains ``AnnotateVideoResponse`` (results). - - Returns: - Callable[[~.AnnotateVideoRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'annotate_video' not in self._stubs: - self._stubs['annotate_video'] = self.grpc_channel.unary_unary( - '/google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService/AnnotateVideo', - request_serializer=video_intelligence.AnnotateVideoRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['annotate_video'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'VideoIntelligenceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py deleted file mode 100644 index ac168dda..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/__init__.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .video_intelligence import ( - AnnotateVideoProgress, - AnnotateVideoRequest, - AnnotateVideoResponse, - Celebrity, - CelebrityRecognitionAnnotation, - CelebrityTrack, - DetectedAttribute, - DetectedLandmark, - Entity, - ExplicitContentAnnotation, - ExplicitContentDetectionConfig, - ExplicitContentFrame, - FaceDetectionAnnotation, - FaceDetectionConfig, - LabelAnnotation, - LabelDetectionConfig, - LabelFrame, - LabelSegment, - LogoRecognitionAnnotation, - NormalizedBoundingBox, - NormalizedBoundingPoly, - NormalizedVertex, - ObjectTrackingAnnotation, - ObjectTrackingConfig, - ObjectTrackingFrame, - PersonDetectionAnnotation, - PersonDetectionConfig, - ShotChangeDetectionConfig, - SpeechContext, - SpeechRecognitionAlternative, - SpeechTranscription, - SpeechTranscriptionConfig, - StreamingAnnotateVideoRequest, - StreamingAnnotateVideoResponse, - StreamingAutomlActionRecognitionConfig, - StreamingAutomlClassificationConfig, - StreamingAutomlObjectTrackingConfig, - StreamingExplicitContentDetectionConfig, - StreamingLabelDetectionConfig, - StreamingObjectTrackingConfig, - StreamingShotChangeDetectionConfig, - StreamingStorageConfig, - StreamingVideoAnnotationResults, - StreamingVideoConfig, - TextAnnotation, - TextDetectionConfig, - TextFrame, - TextSegment, - TimestampedObject, - Track, - VideoAnnotationProgress, - VideoAnnotationResults, - VideoContext, - VideoSegment, - WordInfo, - Feature, - LabelDetectionMode, - Likelihood, - StreamingFeature, -) - -__all__ = ( - 'AnnotateVideoProgress', - 'AnnotateVideoRequest', - 'AnnotateVideoResponse', - 'Celebrity', - 'CelebrityRecognitionAnnotation', - 'CelebrityTrack', - 'DetectedAttribute', - 'DetectedLandmark', - 'Entity', - 'ExplicitContentAnnotation', - 'ExplicitContentDetectionConfig', - 'ExplicitContentFrame', - 'FaceDetectionAnnotation', - 'FaceDetectionConfig', - 'LabelAnnotation', - 'LabelDetectionConfig', - 'LabelFrame', - 'LabelSegment', - 'LogoRecognitionAnnotation', - 'NormalizedBoundingBox', - 'NormalizedBoundingPoly', - 'NormalizedVertex', - 'ObjectTrackingAnnotation', - 'ObjectTrackingConfig', - 'ObjectTrackingFrame', - 'PersonDetectionAnnotation', - 'PersonDetectionConfig', - 'ShotChangeDetectionConfig', - 'SpeechContext', - 'SpeechRecognitionAlternative', - 'SpeechTranscription', - 'SpeechTranscriptionConfig', - 'StreamingAnnotateVideoRequest', - 'StreamingAnnotateVideoResponse', - 'StreamingAutomlActionRecognitionConfig', - 'StreamingAutomlClassificationConfig', - 'StreamingAutomlObjectTrackingConfig', - 'StreamingExplicitContentDetectionConfig', - 'StreamingLabelDetectionConfig', - 'StreamingObjectTrackingConfig', - 'StreamingShotChangeDetectionConfig', - 'StreamingStorageConfig', - 'StreamingVideoAnnotationResults', - 'StreamingVideoConfig', - 'TextAnnotation', - 'TextDetectionConfig', - 'TextFrame', - 'TextSegment', - 'TimestampedObject', - 'Track', - 'VideoAnnotationProgress', - 'VideoAnnotationResults', - 'VideoContext', - 'VideoSegment', - 'WordInfo', - 'Feature', - 'LabelDetectionMode', - 'Likelihood', - 'StreamingFeature', -) diff --git a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py b/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py deleted file mode 100644 index 9786033a..00000000 --- a/owl-bot-staging/v1p3beta1/google/cloud/videointelligence_v1p3beta1/types/video_intelligence.py +++ /dev/null @@ -1,1998 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.videointelligence.v1p3beta1', - manifest={ - 'LabelDetectionMode', - 'Likelihood', - 'StreamingFeature', - 'Feature', - 'AnnotateVideoRequest', - 'VideoContext', - 'LabelDetectionConfig', - 'ShotChangeDetectionConfig', - 'ObjectTrackingConfig', - 'ExplicitContentDetectionConfig', - 'FaceDetectionConfig', - 'PersonDetectionConfig', - 'TextDetectionConfig', - 'VideoSegment', - 'LabelSegment', - 'LabelFrame', - 'Entity', - 'LabelAnnotation', - 'ExplicitContentFrame', - 'ExplicitContentAnnotation', - 'NormalizedBoundingBox', - 'TimestampedObject', - 'Track', - 'DetectedAttribute', - 'Celebrity', - 'CelebrityTrack', - 'CelebrityRecognitionAnnotation', - 'DetectedLandmark', - 'FaceDetectionAnnotation', - 'PersonDetectionAnnotation', - 'VideoAnnotationResults', - 'AnnotateVideoResponse', - 'VideoAnnotationProgress', - 'AnnotateVideoProgress', - 'SpeechTranscriptionConfig', - 'SpeechContext', - 'SpeechTranscription', - 'SpeechRecognitionAlternative', - 'WordInfo', - 'NormalizedVertex', - 'NormalizedBoundingPoly', - 'TextSegment', - 'TextFrame', - 'TextAnnotation', - 'ObjectTrackingFrame', - 'ObjectTrackingAnnotation', - 'LogoRecognitionAnnotation', - 'StreamingAnnotateVideoRequest', - 'StreamingVideoConfig', - 'StreamingAnnotateVideoResponse', - 'StreamingVideoAnnotationResults', - 'StreamingShotChangeDetectionConfig', - 'StreamingLabelDetectionConfig', - 'StreamingExplicitContentDetectionConfig', - 'StreamingObjectTrackingConfig', - 'StreamingAutomlActionRecognitionConfig', - 'StreamingAutomlClassificationConfig', - 'StreamingAutomlObjectTrackingConfig', - 'StreamingStorageConfig', - }, -) - - -class LabelDetectionMode(proto.Enum): - r"""Label detection mode.""" - LABEL_DETECTION_MODE_UNSPECIFIED = 0 - SHOT_MODE = 1 - FRAME_MODE = 2 - SHOT_AND_FRAME_MODE = 3 - - -class Likelihood(proto.Enum): - r"""Bucketized representation of likelihood.""" - LIKELIHOOD_UNSPECIFIED = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class StreamingFeature(proto.Enum): - r"""Streaming video annotation feature.""" - STREAMING_FEATURE_UNSPECIFIED = 0 - STREAMING_LABEL_DETECTION = 1 - STREAMING_SHOT_CHANGE_DETECTION = 2 - STREAMING_EXPLICIT_CONTENT_DETECTION = 3 - STREAMING_OBJECT_TRACKING = 4 - STREAMING_AUTOML_ACTION_RECOGNITION = 23 - STREAMING_AUTOML_CLASSIFICATION = 21 - STREAMING_AUTOML_OBJECT_TRACKING = 22 - - -class Feature(proto.Enum): - r"""Video annotation feature.""" - FEATURE_UNSPECIFIED = 0 - LABEL_DETECTION = 1 - SHOT_CHANGE_DETECTION = 2 - EXPLICIT_CONTENT_DETECTION = 3 - FACE_DETECTION = 4 - SPEECH_TRANSCRIPTION = 6 - TEXT_DETECTION = 7 - OBJECT_TRACKING = 9 - LOGO_RECOGNITION = 12 - CELEBRITY_RECOGNITION = 13 - PERSON_DETECTION = 14 - - -class AnnotateVideoRequest(proto.Message): - r"""Video annotation request. - - Attributes: - input_uri (str): - Input video location. Currently, only `Cloud - Storage `__ URIs are - supported. URIs must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - To identify multiple videos, a video URI may include - wildcards in the ``object-id``. Supported wildcards: '*' to - match 0 or more characters; '?' to match 1 character. If - unset, the input video should be embedded in the request as - ``input_content``. If set, ``input_content`` must be unset. - input_content (bytes): - The video data bytes. If unset, the input video(s) should be - specified via the ``input_uri``. If set, ``input_uri`` must - be unset. - features (Sequence[google.cloud.videointelligence_v1p3beta1.types.Feature]): - Required. Requested video annotation - features. - video_context (google.cloud.videointelligence_v1p3beta1.types.VideoContext): - Additional video context and/or feature- - pecific parameters. - output_uri (str): - Optional. Location where the output (in JSON format) should - be stored. Currently, only `Cloud - Storage `__ URIs are - supported. These must be specified in the following format: - ``gs://bucket-id/object-id`` (other URI formats return - [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). - For more information, see `Request - URIs `__. - location_id (str): - Optional. Cloud region where annotation should take place. - Supported cloud regions are: ``us-east1``, ``us-west1``, - ``europe-west1``, ``asia-east1``. If no region is specified, - the region will be determined based on video file location. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - input_content = proto.Field( - proto.BYTES, - number=6, - ) - features = proto.RepeatedField( - proto.ENUM, - number=2, - enum='Feature', - ) - video_context = proto.Field( - proto.MESSAGE, - number=3, - message='VideoContext', - ) - output_uri = proto.Field( - proto.STRING, - number=4, - ) - location_id = proto.Field( - proto.STRING, - number=5, - ) - - -class VideoContext(proto.Message): - r"""Video context and/or feature-specific parameters. - - Attributes: - segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): - Video segments to annotate. The segments may - overlap and are not required to be contiguous or - span the whole video. If unspecified, each video - is treated as a single segment. - label_detection_config (google.cloud.videointelligence_v1p3beta1.types.LabelDetectionConfig): - Config for LABEL_DETECTION. - shot_change_detection_config (google.cloud.videointelligence_v1p3beta1.types.ShotChangeDetectionConfig): - Config for SHOT_CHANGE_DETECTION. - explicit_content_detection_config (google.cloud.videointelligence_v1p3beta1.types.ExplicitContentDetectionConfig): - Config for EXPLICIT_CONTENT_DETECTION. - face_detection_config (google.cloud.videointelligence_v1p3beta1.types.FaceDetectionConfig): - Config for FACE_DETECTION. - speech_transcription_config (google.cloud.videointelligence_v1p3beta1.types.SpeechTranscriptionConfig): - Config for SPEECH_TRANSCRIPTION. - text_detection_config (google.cloud.videointelligence_v1p3beta1.types.TextDetectionConfig): - Config for TEXT_DETECTION. - person_detection_config (google.cloud.videointelligence_v1p3beta1.types.PersonDetectionConfig): - Config for PERSON_DETECTION. - object_tracking_config (google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingConfig): - Config for OBJECT_TRACKING. - """ - - segments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - label_detection_config = proto.Field( - proto.MESSAGE, - number=2, - message='LabelDetectionConfig', - ) - shot_change_detection_config = proto.Field( - proto.MESSAGE, - number=3, - message='ShotChangeDetectionConfig', - ) - explicit_content_detection_config = proto.Field( - proto.MESSAGE, - number=4, - message='ExplicitContentDetectionConfig', - ) - face_detection_config = proto.Field( - proto.MESSAGE, - number=5, - message='FaceDetectionConfig', - ) - speech_transcription_config = proto.Field( - proto.MESSAGE, - number=6, - message='SpeechTranscriptionConfig', - ) - text_detection_config = proto.Field( - proto.MESSAGE, - number=8, - message='TextDetectionConfig', - ) - person_detection_config = proto.Field( - proto.MESSAGE, - number=11, - message='PersonDetectionConfig', - ) - object_tracking_config = proto.Field( - proto.MESSAGE, - number=13, - message='ObjectTrackingConfig', - ) - - -class LabelDetectionConfig(proto.Message): - r"""Config for LABEL_DETECTION. - - Attributes: - label_detection_mode (google.cloud.videointelligence_v1p3beta1.types.LabelDetectionMode): - What labels should be detected with LABEL_DETECTION, in - addition to video-level labels or segment-level labels. If - unspecified, defaults to ``SHOT_MODE``. - stationary_camera (bool): - Whether the video has been shot from a stationary (i.e., - non-moving) camera. When set to true, might improve - detection accuracy for moving objects. Should be used with - ``SHOT_AND_FRAME_MODE`` enabled. - model (str): - Model to use for label detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - frame_confidence_threshold (float): - The confidence threshold we perform filtering on the labels - from frame-level detection. If not set, it is set to 0.4 by - default. The valid range for this threshold is [0.1, 0.9]. - Any value set outside of this range will be clipped. Note: - For best results, follow the default threshold. We will - update the default threshold everytime when we release a new - model. - video_confidence_threshold (float): - The confidence threshold we perform filtering on the labels - from video-level and shot-level detections. If not set, it's - set to 0.3 by default. The valid range for this threshold is - [0.1, 0.9]. Any value set outside of this range will be - clipped. Note: For best results, follow the default - threshold. We will update the default threshold everytime - when we release a new model. - """ - - label_detection_mode = proto.Field( - proto.ENUM, - number=1, - enum='LabelDetectionMode', - ) - stationary_camera = proto.Field( - proto.BOOL, - number=2, - ) - model = proto.Field( - proto.STRING, - number=3, - ) - frame_confidence_threshold = proto.Field( - proto.FLOAT, - number=4, - ) - video_confidence_threshold = proto.Field( - proto.FLOAT, - number=5, - ) - - -class ShotChangeDetectionConfig(proto.Message): - r"""Config for SHOT_CHANGE_DETECTION. - - Attributes: - model (str): - Model to use for shot change detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class ObjectTrackingConfig(proto.Message): - r"""Config for OBJECT_TRACKING. - - Attributes: - model (str): - Model to use for object tracking. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class ExplicitContentDetectionConfig(proto.Message): - r"""Config for EXPLICIT_CONTENT_DETECTION. - - Attributes: - model (str): - Model to use for explicit content detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - - -class FaceDetectionConfig(proto.Message): - r"""Config for FACE_DETECTION. - - Attributes: - model (str): - Model to use for face detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - include_bounding_boxes (bool): - Whether bounding boxes are included in the - face annotation output. - include_attributes (bool): - Whether to enable face attributes detection, such as - glasses, dark_glasses, mouth_open etc. Ignored if - 'include_bounding_boxes' is set to false. - """ - - model = proto.Field( - proto.STRING, - number=1, - ) - include_bounding_boxes = proto.Field( - proto.BOOL, - number=2, - ) - include_attributes = proto.Field( - proto.BOOL, - number=5, - ) - - -class PersonDetectionConfig(proto.Message): - r"""Config for PERSON_DETECTION. - - Attributes: - include_bounding_boxes (bool): - Whether bounding boxes are included in the - person detection annotation output. - include_pose_landmarks (bool): - Whether to enable pose landmarks detection. Ignored if - 'include_bounding_boxes' is set to false. - include_attributes (bool): - Whether to enable person attributes detection, such as cloth - color (black, blue, etc), type (coat, dress, etc), pattern - (plain, floral, etc), hair, etc. Ignored if - 'include_bounding_boxes' is set to false. - """ - - include_bounding_boxes = proto.Field( - proto.BOOL, - number=1, - ) - include_pose_landmarks = proto.Field( - proto.BOOL, - number=2, - ) - include_attributes = proto.Field( - proto.BOOL, - number=3, - ) - - -class TextDetectionConfig(proto.Message): - r"""Config for TEXT_DETECTION. - - Attributes: - language_hints (Sequence[str]): - Language hint can be specified if the - language to be detected is known a priori. It - can increase the accuracy of the detection. - Language hint must be language code in BCP-47 - format. - - Automatic language detection is performed if no - hint is provided. - model (str): - Model to use for text detection. - Supported values: "builtin/stable" (the default - if unset) and "builtin/latest". - """ - - language_hints = proto.RepeatedField( - proto.STRING, - number=1, - ) - model = proto.Field( - proto.STRING, - number=2, - ) - - -class VideoSegment(proto.Message): - r"""Video segment. - - Attributes: - start_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the start of the segment - (inclusive). - end_time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the end of the segment - (inclusive). - """ - - start_time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class LabelSegment(proto.Message): - r"""Video segment level annotation results for label detection. - - Attributes: - segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): - Video segment where a label was detected. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class LabelFrame(proto.Message): - r"""Video frame level annotation results for label detection. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - confidence (float): - Confidence that the label is accurate. Range: [0, 1]. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - -class Entity(proto.Message): - r"""Detected entity from video analysis. - - Attributes: - entity_id (str): - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search - API `__. - description (str): - Textual description, e.g., ``Fixed-gear bicycle``. - language_code (str): - Language code for ``description`` in BCP-47 format. - """ - - entity_id = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class LabelAnnotation(proto.Message): - r"""Label annotation. - - Attributes: - entity (google.cloud.videointelligence_v1p3beta1.types.Entity): - Detected entity. - category_entities (Sequence[google.cloud.videointelligence_v1p3beta1.types.Entity]): - Common categories for the detected entity. For example, when - the label is ``Terrier``, the category is likely ``dog``. - And in some cases there might be more than one categories - e.g., ``Terrier`` could also be a ``pet``. - segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelSegment]): - All video segments where a label was - detected. - frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelFrame]): - All video frames where a label was detected. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - category_entities = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Entity', - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelSegment', - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelFrame', - ) - - -class ExplicitContentFrame(proto.Message): - r"""Video frame level annotation results for explicit content. - - Attributes: - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - location. - pornography_likelihood (google.cloud.videointelligence_v1p3beta1.types.Likelihood): - Likelihood of the pornography content.. - """ - - time_offset = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - pornography_likelihood = proto.Field( - proto.ENUM, - number=2, - enum='Likelihood', - ) - - -class ExplicitContentAnnotation(proto.Message): - r"""Explicit content annotation (based on per-frame visual - signals only). If no explicit content has been detected in a - frame, no annotations are present for that frame. - - Attributes: - frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.ExplicitContentFrame]): - All video frames where explicit content was - detected. - """ - - frames = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExplicitContentFrame', - ) - - -class NormalizedBoundingBox(proto.Message): - r"""Normalized bounding box. The normalized vertex coordinates are - relative to the original image. Range: [0, 1]. - - Attributes: - left (float): - Left X coordinate. - top (float): - Top Y coordinate. - right (float): - Right X coordinate. - bottom (float): - Bottom Y coordinate. - """ - - left = proto.Field( - proto.FLOAT, - number=1, - ) - top = proto.Field( - proto.FLOAT, - number=2, - ) - right = proto.Field( - proto.FLOAT, - number=3, - ) - bottom = proto.Field( - proto.FLOAT, - number=4, - ) - - -class TimestampedObject(proto.Message): - r"""For tracking related features. An object at time_offset with - attributes, and located with normalized_bounding_box. - - Attributes: - normalized_bounding_box (google.cloud.videointelligence_v1p3beta1.types.NormalizedBoundingBox): - Normalized Bounding box in a frame, where the - object is located. - time_offset (google.protobuf.duration_pb2.Duration): - Time-offset, relative to the beginning of the - video, corresponding to the video frame for this - object. - attributes (Sequence[google.cloud.videointelligence_v1p3beta1.types.DetectedAttribute]): - Optional. The attributes of the object in the - bounding box. - landmarks (Sequence[google.cloud.videointelligence_v1p3beta1.types.DetectedLandmark]): - Optional. The detected landmarks. - """ - - normalized_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingBox', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - attributes = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='DetectedAttribute', - ) - landmarks = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='DetectedLandmark', - ) - - -class Track(proto.Message): - r"""A track of an object instance. - - Attributes: - segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): - Video segment of a track. - timestamped_objects (Sequence[google.cloud.videointelligence_v1p3beta1.types.TimestampedObject]): - The object with timestamp and attributes per - frame in the track. - attributes (Sequence[google.cloud.videointelligence_v1p3beta1.types.DetectedAttribute]): - Optional. Attributes in the track level. - confidence (float): - Optional. The confidence score of the tracked - object. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - timestamped_objects = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TimestampedObject', - ) - attributes = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='DetectedAttribute', - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - - -class DetectedAttribute(proto.Message): - r"""A generic detected attribute represented by name in string - format. - - Attributes: - name (str): - The name of the attribute, for example, glasses, - dark_glasses, mouth_open. A full list of supported type - names will be provided in the document. - confidence (float): - Detected attribute confidence. Range [0, 1]. - value (str): - Text value of the detection result. For - example, the value for "HairColor" can be - "black", "blonde", etc. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - value = proto.Field( - proto.STRING, - number=3, - ) - - -class Celebrity(proto.Message): - r"""Celebrity definition. - - Attributes: - name (str): - The resource name of the celebrity. Have the format - ``video-intelligence/kg-mid`` indicates a celebrity from - preloaded gallery. kg-mid is the id in Google knowledge - graph, which is unique for the celebrity. - display_name (str): - The celebrity name. - description (str): - Textual description of additional information - about the celebrity, if applicable. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - - -class CelebrityTrack(proto.Message): - r"""The annotation result of a celebrity face track. - RecognizedCelebrity field could be empty if the face track does - not have any matched celebrities. - - Attributes: - celebrities (Sequence[google.cloud.videointelligence_v1p3beta1.types.CelebrityTrack.RecognizedCelebrity]): - Top N match of the celebrities for the face - in this track. - face_track (google.cloud.videointelligence_v1p3beta1.types.Track): - A track of a person's face. - """ - - class RecognizedCelebrity(proto.Message): - r"""The recognized celebrity with confidence score. - - Attributes: - celebrity (google.cloud.videointelligence_v1p3beta1.types.Celebrity): - The recognized celebrity. - confidence (float): - Recognition confidence. Range [0, 1]. - """ - - celebrity = proto.Field( - proto.MESSAGE, - number=1, - message='Celebrity', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - - celebrities = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=RecognizedCelebrity, - ) - face_track = proto.Field( - proto.MESSAGE, - number=3, - message='Track', - ) - - -class CelebrityRecognitionAnnotation(proto.Message): - r"""Celebrity recognition annotation per video. - - Attributes: - celebrity_tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.CelebrityTrack]): - The tracks detected from the input video, - including recognized celebrities and other - detected faces in the video. - """ - - celebrity_tracks = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CelebrityTrack', - ) - - -class DetectedLandmark(proto.Message): - r"""A generic detected landmark represented by name in string - format and a 2D location. - - Attributes: - name (str): - The name of this landmark, for example, left_hand, - right_shoulder. - point (google.cloud.videointelligence_v1p3beta1.types.NormalizedVertex): - The 2D point of the detected landmark using - the normalized image coordindate system. The - normalized coordinates have the range from 0 to - 1. - confidence (float): - The confidence score of the detected landmark. Range [0, 1]. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - point = proto.Field( - proto.MESSAGE, - number=2, - message='NormalizedVertex', - ) - confidence = proto.Field( - proto.FLOAT, - number=3, - ) - - -class FaceDetectionAnnotation(proto.Message): - r"""Face detection annotation. - - Attributes: - tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): - The face tracks with attributes. - thumbnail (bytes): - The thumbnail of a person's face. - """ - - tracks = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Track', - ) - thumbnail = proto.Field( - proto.BYTES, - number=4, - ) - - -class PersonDetectionAnnotation(proto.Message): - r"""Person detection annotation per video. - - Attributes: - tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): - The detected tracks of a person. - """ - - tracks = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Track', - ) - - -class VideoAnnotationResults(proto.Message): - r"""Annotation results for a single video. - - Attributes: - input_uri (str): - Video file location in `Cloud - Storage `__. - segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): - Video segment on which the annotation is run. - segment_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): - Topical label annotations on video level or - user-specified segment level. There is exactly - one element for each unique label. - segment_presence_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): - Presence label annotations on video level or user-specified - segment level. There is exactly one element for each unique - label. Compared to the existing topical - ``segment_label_annotations``, this field presents more - fine-grained, segment-level labels detected in video content - and is made available only when the client sets - ``LabelDetectionConfig.model`` to "builtin/latest" in the - request. - shot_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): - Topical label annotations on shot level. - There is exactly one element for each unique - label. - shot_presence_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): - Presence label annotations on shot level. There is exactly - one element for each unique label. Compared to the existing - topical ``shot_label_annotations``, this field presents more - fine-grained, shot-level labels detected in video content - and is made available only when the client sets - ``LabelDetectionConfig.model`` to "builtin/latest" in the - request. - frame_label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): - Label annotations on frame level. - There is exactly one element for each unique - label. - face_detection_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.FaceDetectionAnnotation]): - Face detection annotations. - shot_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): - Shot annotations. Each shot is represented as - a video segment. - explicit_annotation (google.cloud.videointelligence_v1p3beta1.types.ExplicitContentAnnotation): - Explicit content annotation. - speech_transcriptions (Sequence[google.cloud.videointelligence_v1p3beta1.types.SpeechTranscription]): - Speech transcription. - text_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.TextAnnotation]): - OCR text detection and tracking. - Annotations for list of detected text snippets. - Each will have list of frame information - associated with it. - object_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingAnnotation]): - Annotations for list of objects detected and - tracked in video. - logo_recognition_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LogoRecognitionAnnotation]): - Annotations for list of logos detected, - tracked and recognized in video. - person_detection_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.PersonDetectionAnnotation]): - Person detection annotations. - celebrity_recognition_annotations (google.cloud.videointelligence_v1p3beta1.types.CelebrityRecognitionAnnotation): - Celebrity recognition annotations. - error (google.rpc.status_pb2.Status): - If set, indicates an error. Note that for a single - ``AnnotateVideoRequest`` some videos may succeed and some - may fail. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - segment = proto.Field( - proto.MESSAGE, - number=10, - message='VideoSegment', - ) - segment_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='LabelAnnotation', - ) - segment_presence_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=23, - message='LabelAnnotation', - ) - shot_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='LabelAnnotation', - ) - shot_presence_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=24, - message='LabelAnnotation', - ) - frame_label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='LabelAnnotation', - ) - face_detection_annotations = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='FaceDetectionAnnotation', - ) - shot_annotations = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='VideoSegment', - ) - explicit_annotation = proto.Field( - proto.MESSAGE, - number=7, - message='ExplicitContentAnnotation', - ) - speech_transcriptions = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='SpeechTranscription', - ) - text_annotations = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='TextAnnotation', - ) - object_annotations = proto.RepeatedField( - proto.MESSAGE, - number=14, - message='ObjectTrackingAnnotation', - ) - logo_recognition_annotations = proto.RepeatedField( - proto.MESSAGE, - number=19, - message='LogoRecognitionAnnotation', - ) - person_detection_annotations = proto.RepeatedField( - proto.MESSAGE, - number=20, - message='PersonDetectionAnnotation', - ) - celebrity_recognition_annotations = proto.Field( - proto.MESSAGE, - number=21, - message='CelebrityRecognitionAnnotation', - ) - error = proto.Field( - proto.MESSAGE, - number=9, - message=status_pb2.Status, - ) - - -class AnnotateVideoResponse(proto.Message): - r"""Video annotation response. Included in the ``response`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_results (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoAnnotationResults]): - Annotation results for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationResults', - ) - - -class VideoAnnotationProgress(proto.Message): - r"""Annotation progress for a single video. - - Attributes: - input_uri (str): - Video file location in `Cloud - Storage `__. - progress_percent (int): - Approximate percentage processed thus far. - Guaranteed to be 100 when fully processed. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the request was received. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Time of the most recent update. - feature (google.cloud.videointelligence_v1p3beta1.types.Feature): - Specifies which feature is being tracked if - the request contains more than one feature. - segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): - Specifies which segment is being tracked if - the request contains more than one segment. - """ - - input_uri = proto.Field( - proto.STRING, - number=1, - ) - progress_percent = proto.Field( - proto.INT32, - number=2, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - feature = proto.Field( - proto.ENUM, - number=5, - enum='Feature', - ) - segment = proto.Field( - proto.MESSAGE, - number=6, - message='VideoSegment', - ) - - -class AnnotateVideoProgress(proto.Message): - r"""Video annotation progress. Included in the ``metadata`` field of the - ``Operation`` returned by the ``GetOperation`` call of the - ``google::longrunning::Operations`` service. - - Attributes: - annotation_progress (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoAnnotationProgress]): - Progress metadata for all videos specified in - ``AnnotateVideoRequest``. - """ - - annotation_progress = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoAnnotationProgress', - ) - - -class SpeechTranscriptionConfig(proto.Message): - r"""Config for SPEECH_TRANSCRIPTION. - - Attributes: - language_code (str): - Required. *Required* The language of the supplied audio as a - `BCP-47 `__ - language tag. Example: "en-US". See `Language - Support `__ - for a list of the currently supported language codes. - max_alternatives (int): - Optional. Maximum number of recognition hypotheses to be - returned. Specifically, the maximum number of - ``SpeechRecognitionAlternative`` messages within each - ``SpeechTranscription``. The server may return fewer than - ``max_alternatives``. Valid values are ``0``-``30``. A value - of ``0`` or ``1`` will return a maximum of one. If omitted, - will return a maximum of one. - filter_profanity (bool): - Optional. If set to ``true``, the server will attempt to - filter out profanities, replacing all but the initial - character in each filtered word with asterisks, e.g. "f***". - If set to ``false`` or omitted, profanities won't be - filtered out. - speech_contexts (Sequence[google.cloud.videointelligence_v1p3beta1.types.SpeechContext]): - Optional. A means to provide context to - assist the speech recognition. - enable_automatic_punctuation (bool): - Optional. If 'true', adds punctuation to - recognition result hypotheses. This feature is - only available in select languages. Setting this - for requests in other languages has no effect at - all. The default 'false' value does not add - punctuation to result hypotheses. NOTE: "This is - currently offered as an experimental service, - complimentary to all users. In the future this - may be exclusively available as a premium - feature.". - audio_tracks (Sequence[int]): - Optional. For file formats, such as MXF or - MKV, supporting multiple audio tracks, specify - up to two tracks. Default: track 0. - enable_speaker_diarization (bool): - Optional. If 'true', enables speaker detection for each - recognized word in the top alternative of the recognition - result using a speaker_tag provided in the WordInfo. Note: - When this is true, we send all the words from the beginning - of the audio for the top alternative in every consecutive - response. This is done in order to improve our speaker tags - as our models learn to identify the speakers in the - conversation over time. - diarization_speaker_count (int): - Optional. If set, specifies the estimated number of speakers - in the conversation. If not set, defaults to '2'. Ignored - unless enable_speaker_diarization is set to true. - enable_word_confidence (bool): - Optional. If ``true``, the top result includes a list of - words and the confidence for those words. If ``false``, no - word-level confidence information is returned. The default - is ``false``. - """ - - language_code = proto.Field( - proto.STRING, - number=1, - ) - max_alternatives = proto.Field( - proto.INT32, - number=2, - ) - filter_profanity = proto.Field( - proto.BOOL, - number=3, - ) - speech_contexts = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='SpeechContext', - ) - enable_automatic_punctuation = proto.Field( - proto.BOOL, - number=5, - ) - audio_tracks = proto.RepeatedField( - proto.INT32, - number=6, - ) - enable_speaker_diarization = proto.Field( - proto.BOOL, - number=7, - ) - diarization_speaker_count = proto.Field( - proto.INT32, - number=8, - ) - enable_word_confidence = proto.Field( - proto.BOOL, - number=9, - ) - - -class SpeechContext(proto.Message): - r"""Provides "hints" to the speech recognizer to favor specific - words and phrases in the results. - - Attributes: - phrases (Sequence[str]): - Optional. A list of strings containing words and phrases - "hints" so that the speech recognition is more likely to - recognize them. This can be used to improve the accuracy for - specific words and phrases, for example, if specific - commands are typically spoken by the user. This can also be - used to add additional words to the vocabulary of the - recognizer. See `usage - limits `__. - """ - - phrases = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class SpeechTranscription(proto.Message): - r"""A speech recognition result corresponding to a portion of the - audio. - - Attributes: - alternatives (Sequence[google.cloud.videointelligence_v1p3beta1.types.SpeechRecognitionAlternative]): - May contain one or more recognition hypotheses (up to the - maximum specified in ``max_alternatives``). These - alternatives are ordered in terms of accuracy, with the top - (first) alternative being the most probable, as ranked by - the recognizer. - language_code (str): - Output only. The - `BCP-47 `__ - language tag of the language in this result. This language - code was detected to have the most likelihood of being - spoken in the audio. - """ - - alternatives = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SpeechRecognitionAlternative', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class SpeechRecognitionAlternative(proto.Message): - r"""Alternative hypotheses (a.k.a. n-best list). - - Attributes: - transcript (str): - Transcript text representing the words that - the user spoke. - confidence (float): - Output only. The confidence estimate between 0.0 and 1.0. A - higher number indicates an estimated greater likelihood that - the recognized words are correct. This field is set only for - the top alternative. This field is not guaranteed to be - accurate and users should not rely on it to be always - provided. The default of 0.0 is a sentinel value indicating - ``confidence`` was not set. - words (Sequence[google.cloud.videointelligence_v1p3beta1.types.WordInfo]): - Output only. A list of word-specific information for each - recognized word. Note: When ``enable_speaker_diarization`` - is set to true, you will see all the words from the - beginning of the audio. - """ - - transcript = proto.Field( - proto.STRING, - number=1, - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - words = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='WordInfo', - ) - - -class WordInfo(proto.Message): - r"""Word-specific information for recognized words. Word information is - only included in the response when certain request parameters are - set, such as ``enable_word_time_offsets``. - - Attributes: - start_time (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the audio, and - corresponding to the start of the spoken word. This field is - only set if ``enable_word_time_offsets=true`` and only in - the top hypothesis. This is an experimental feature and the - accuracy of the time offset can vary. - end_time (google.protobuf.duration_pb2.Duration): - Time offset relative to the beginning of the audio, and - corresponding to the end of the spoken word. This field is - only set if ``enable_word_time_offsets=true`` and only in - the top hypothesis. This is an experimental feature and the - accuracy of the time offset can vary. - word (str): - The word corresponding to this set of - information. - confidence (float): - Output only. The confidence estimate between 0.0 and 1.0. A - higher number indicates an estimated greater likelihood that - the recognized words are correct. This field is set only for - the top alternative. This field is not guaranteed to be - accurate and users should not rely on it to be always - provided. The default of 0.0 is a sentinel value indicating - ``confidence`` was not set. - speaker_tag (int): - Output only. A distinct integer value is assigned for every - speaker within the audio. This field specifies which one of - those speakers was detected to have spoken this word. Value - ranges from 1 up to diarization_speaker_count, and is only - set if speaker diarization is enabled. - """ - - start_time = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - end_time = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - word = proto.Field( - proto.STRING, - number=3, - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - speaker_tag = proto.Field( - proto.INT32, - number=5, - ) - - -class NormalizedVertex(proto.Message): - r"""A vertex represents a 2D point in the image. - NOTE: the normalized vertex coordinates are relative to the - original image and range from 0 to 1. - - Attributes: - x (float): - X coordinate. - y (float): - Y coordinate. - """ - - x = proto.Field( - proto.FLOAT, - number=1, - ) - y = proto.Field( - proto.FLOAT, - number=2, - ) - - -class NormalizedBoundingPoly(proto.Message): - r"""Normalized bounding polygon for text (that might not be aligned with - axis). Contains list of the corner points in clockwise order - starting from top-left corner. For example, for a rectangular - bounding box: When the text is horizontal it might look like: 0----1 - \| \| 3----2 - - When it's clockwise rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 - - and the vertex order will still be (0, 1, 2, 3). Note that values - can be less than 0, or greater than 1 due to trignometric - calculations for location of the box. - - Attributes: - vertices (Sequence[google.cloud.videointelligence_v1p3beta1.types.NormalizedVertex]): - Normalized vertices of the bounding polygon. - """ - - vertices = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='NormalizedVertex', - ) - - -class TextSegment(proto.Message): - r"""Video segment level annotation results for text detection. - - Attributes: - segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): - Video segment where a text snippet was - detected. - confidence (float): - Confidence for the track of detected text. It - is calculated as the highest over all frames - where OCR detected text appears. - frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.TextFrame]): - Information related to the frames where OCR - detected text appears. - """ - - segment = proto.Field( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - confidence = proto.Field( - proto.FLOAT, - number=2, - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='TextFrame', - ) - - -class TextFrame(proto.Message): - r"""Video frame level annotation results for text annotation - (OCR). Contains information regarding timestamp and bounding box - locations for the frames containing detected OCR text snippets. - - Attributes: - rotated_bounding_box (google.cloud.videointelligence_v1p3beta1.types.NormalizedBoundingPoly): - Bounding polygon of the detected text for - this frame. - time_offset (google.protobuf.duration_pb2.Duration): - Timestamp of this frame. - """ - - rotated_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingPoly', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class TextAnnotation(proto.Message): - r"""Annotations related to one detected OCR text snippet. This - will contain the corresponding text, confidence value, and frame - level information for each detection. - - Attributes: - text (str): - The detected text. - segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.TextSegment]): - All video segments where OCR detected text - appears. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TextSegment', - ) - - -class ObjectTrackingFrame(proto.Message): - r"""Video frame level annotations for object detection and - tracking. This field stores per frame location, time offset, and - confidence. - - Attributes: - normalized_bounding_box (google.cloud.videointelligence_v1p3beta1.types.NormalizedBoundingBox): - The normalized bounding box location of this - object track for the frame. - time_offset (google.protobuf.duration_pb2.Duration): - The timestamp of the frame in microseconds. - """ - - normalized_bounding_box = proto.Field( - proto.MESSAGE, - number=1, - message='NormalizedBoundingBox', - ) - time_offset = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class ObjectTrackingAnnotation(proto.Message): - r"""Annotations corresponding to one tracked object. - - Attributes: - segment (google.cloud.videointelligence_v1p3beta1.types.VideoSegment): - Non-streaming batch mode ONLY. - Each object track corresponds to one video - segment where it appears. - track_id (int): - Streaming mode ONLY. In streaming mode, we do not know the - end time of a tracked object before it is completed. Hence, - there is no VideoSegment info returned. Instead, we provide - a unique identifiable integer track_id so that the customers - can correlate the results of the ongoing - ObjectTrackAnnotation of the same track_id over time. - entity (google.cloud.videointelligence_v1p3beta1.types.Entity): - Entity to specify the object category that - this track is labeled as. - confidence (float): - Object category's labeling confidence of this - track. - frames (Sequence[google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingFrame]): - Information corresponding to all frames where - this object track appears. Non-streaming batch - mode: it may be one or multiple - ObjectTrackingFrame messages in frames. - Streaming mode: it can only be one - ObjectTrackingFrame message in frames. - """ - - segment = proto.Field( - proto.MESSAGE, - number=3, - oneof='track_info', - message='VideoSegment', - ) - track_id = proto.Field( - proto.INT64, - number=5, - oneof='track_info', - ) - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - frames = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ObjectTrackingFrame', - ) - - -class LogoRecognitionAnnotation(proto.Message): - r"""Annotation corresponding to one detected, tracked and - recognized logo class. - - Attributes: - entity (google.cloud.videointelligence_v1p3beta1.types.Entity): - Entity category information to specify the - logo class that all the logo tracks within this - LogoRecognitionAnnotation are recognized as. - tracks (Sequence[google.cloud.videointelligence_v1p3beta1.types.Track]): - All logo tracks where the recognized logo - appears. Each track corresponds to one logo - instance appearing in consecutive frames. - segments (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): - All video segments where the recognized logo - appears. There might be multiple instances of - the same logo class appearing in one - VideoSegment. - """ - - entity = proto.Field( - proto.MESSAGE, - number=1, - message='Entity', - ) - tracks = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Track', - ) - segments = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='VideoSegment', - ) - - -class StreamingAnnotateVideoRequest(proto.Message): - r"""The top-level message sent by the client for the - ``StreamingAnnotateVideo`` method. Multiple - ``StreamingAnnotateVideoRequest`` messages are sent. The first - message must only contain a ``StreamingVideoConfig`` message. All - subsequent messages must only contain ``input_content`` data. - - Attributes: - video_config (google.cloud.videointelligence_v1p3beta1.types.StreamingVideoConfig): - Provides information to the annotator, specifing how to - process the request. The first - ``AnnotateStreamingVideoRequest`` message must only contain - a ``video_config`` message. - input_content (bytes): - The video data to be annotated. Chunks of video data are - sequentially sent in ``StreamingAnnotateVideoRequest`` - messages. Except the initial - ``StreamingAnnotateVideoRequest`` message containing only - ``video_config``, all subsequent - ``AnnotateStreamingVideoRequest`` messages must only contain - ``input_content`` field. Note: as with all bytes fields, - protobuffers use a pure binary representation (not base64). - """ - - video_config = proto.Field( - proto.MESSAGE, - number=1, - oneof='streaming_request', - message='StreamingVideoConfig', - ) - input_content = proto.Field( - proto.BYTES, - number=2, - oneof='streaming_request', - ) - - -class StreamingVideoConfig(proto.Message): - r"""Provides information to the annotator that specifies how to - process the request. - - Attributes: - shot_change_detection_config (google.cloud.videointelligence_v1p3beta1.types.StreamingShotChangeDetectionConfig): - Config for STREAMING_SHOT_CHANGE_DETECTION. - label_detection_config (google.cloud.videointelligence_v1p3beta1.types.StreamingLabelDetectionConfig): - Config for STREAMING_LABEL_DETECTION. - explicit_content_detection_config (google.cloud.videointelligence_v1p3beta1.types.StreamingExplicitContentDetectionConfig): - Config for STREAMING_EXPLICIT_CONTENT_DETECTION. - object_tracking_config (google.cloud.videointelligence_v1p3beta1.types.StreamingObjectTrackingConfig): - Config for STREAMING_OBJECT_TRACKING. - automl_action_recognition_config (google.cloud.videointelligence_v1p3beta1.types.StreamingAutomlActionRecognitionConfig): - Config for STREAMING_AUTOML_ACTION_RECOGNITION. - automl_classification_config (google.cloud.videointelligence_v1p3beta1.types.StreamingAutomlClassificationConfig): - Config for STREAMING_AUTOML_CLASSIFICATION. - automl_object_tracking_config (google.cloud.videointelligence_v1p3beta1.types.StreamingAutomlObjectTrackingConfig): - Config for STREAMING_AUTOML_OBJECT_TRACKING. - feature (google.cloud.videointelligence_v1p3beta1.types.StreamingFeature): - Requested annotation feature. - storage_config (google.cloud.videointelligence_v1p3beta1.types.StreamingStorageConfig): - Streaming storage option. By default: storage - is disabled. - """ - - shot_change_detection_config = proto.Field( - proto.MESSAGE, - number=2, - oneof='streaming_config', - message='StreamingShotChangeDetectionConfig', - ) - label_detection_config = proto.Field( - proto.MESSAGE, - number=3, - oneof='streaming_config', - message='StreamingLabelDetectionConfig', - ) - explicit_content_detection_config = proto.Field( - proto.MESSAGE, - number=4, - oneof='streaming_config', - message='StreamingExplicitContentDetectionConfig', - ) - object_tracking_config = proto.Field( - proto.MESSAGE, - number=5, - oneof='streaming_config', - message='StreamingObjectTrackingConfig', - ) - automl_action_recognition_config = proto.Field( - proto.MESSAGE, - number=23, - oneof='streaming_config', - message='StreamingAutomlActionRecognitionConfig', - ) - automl_classification_config = proto.Field( - proto.MESSAGE, - number=21, - oneof='streaming_config', - message='StreamingAutomlClassificationConfig', - ) - automl_object_tracking_config = proto.Field( - proto.MESSAGE, - number=22, - oneof='streaming_config', - message='StreamingAutomlObjectTrackingConfig', - ) - feature = proto.Field( - proto.ENUM, - number=1, - enum='StreamingFeature', - ) - storage_config = proto.Field( - proto.MESSAGE, - number=30, - message='StreamingStorageConfig', - ) - - -class StreamingAnnotateVideoResponse(proto.Message): - r"""``StreamingAnnotateVideoResponse`` is the only message returned to - the client by ``StreamingAnnotateVideo``. A series of zero or more - ``StreamingAnnotateVideoResponse`` messages are streamed back to the - client. - - Attributes: - error (google.rpc.status_pb2.Status): - If set, returns a [google.rpc.Status][google.rpc.Status] - message that specifies the error for the operation. - annotation_results (google.cloud.videointelligence_v1p3beta1.types.StreamingVideoAnnotationResults): - Streaming annotation results. - annotation_results_uri (str): - Google Cloud Storage(GCS) URI that stores annotation results - of one streaming session in JSON format. It is the - annotation_result_storage_directory from the request - followed by '/cloud_project_number-session_id'. - """ - - error = proto.Field( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - annotation_results = proto.Field( - proto.MESSAGE, - number=2, - message='StreamingVideoAnnotationResults', - ) - annotation_results_uri = proto.Field( - proto.STRING, - number=3, - ) - - -class StreamingVideoAnnotationResults(proto.Message): - r"""Streaming annotation results corresponding to a portion of - the video that is currently being processed. - - Attributes: - shot_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.VideoSegment]): - Shot annotation results. Each shot is - represented as a video segment. - label_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.LabelAnnotation]): - Label annotation results. - explicit_annotation (google.cloud.videointelligence_v1p3beta1.types.ExplicitContentAnnotation): - Explicit content annotation results. - object_annotations (Sequence[google.cloud.videointelligence_v1p3beta1.types.ObjectTrackingAnnotation]): - Object tracking results. - """ - - shot_annotations = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VideoSegment', - ) - label_annotations = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='LabelAnnotation', - ) - explicit_annotation = proto.Field( - proto.MESSAGE, - number=3, - message='ExplicitContentAnnotation', - ) - object_annotations = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='ObjectTrackingAnnotation', - ) - - -class StreamingShotChangeDetectionConfig(proto.Message): - r"""Config for STREAMING_SHOT_CHANGE_DETECTION. - """ - - -class StreamingLabelDetectionConfig(proto.Message): - r"""Config for STREAMING_LABEL_DETECTION. - - Attributes: - stationary_camera (bool): - Whether the video has been captured from a - stationary (i.e. non-moving) camera. When set to - true, might improve detection accuracy for - moving objects. Default: false. - """ - - stationary_camera = proto.Field( - proto.BOOL, - number=1, - ) - - -class StreamingExplicitContentDetectionConfig(proto.Message): - r"""Config for STREAMING_EXPLICIT_CONTENT_DETECTION. - """ - - -class StreamingObjectTrackingConfig(proto.Message): - r"""Config for STREAMING_OBJECT_TRACKING. - """ - - -class StreamingAutomlActionRecognitionConfig(proto.Message): - r"""Config for STREAMING_AUTOML_ACTION_RECOGNITION. - - Attributes: - model_name (str): - Resource name of AutoML model. Format: - ``projects/{project_id}/locations/{location_id}/models/{model_id}`` - """ - - model_name = proto.Field( - proto.STRING, - number=1, - ) - - -class StreamingAutomlClassificationConfig(proto.Message): - r"""Config for STREAMING_AUTOML_CLASSIFICATION. - - Attributes: - model_name (str): - Resource name of AutoML model. Format: - ``projects/{project_number}/locations/{location_id}/models/{model_id}`` - """ - - model_name = proto.Field( - proto.STRING, - number=1, - ) - - -class StreamingAutomlObjectTrackingConfig(proto.Message): - r"""Config for STREAMING_AUTOML_OBJECT_TRACKING. - - Attributes: - model_name (str): - Resource name of AutoML model. Format: - ``projects/{project_id}/locations/{location_id}/models/{model_id}`` - """ - - model_name = proto.Field( - proto.STRING, - number=1, - ) - - -class StreamingStorageConfig(proto.Message): - r"""Config for streaming storage option. - - Attributes: - enable_storage_annotation_result (bool): - Enable streaming storage. Default: false. - annotation_result_storage_directory (str): - Cloud Storage URI to store all annotation results for one - client. Client should specify this field as the top-level - storage directory. Annotation results of different sessions - will be put into different sub-directories denoted by - project_name and session_id. All sub-directories will be - auto generated by program and will be made accessible to - client in response proto. URIs must be specified in the - following format: ``gs://bucket-id/object-id`` ``bucket-id`` - should be a valid Cloud Storage bucket created by client and - bucket permission shall also be configured properly. - ``object-id`` can be arbitrary string that make sense to - client. Other URI formats will return error and cause Cloud - Storage write failure. - """ - - enable_storage_annotation_result = proto.Field( - proto.BOOL, - number=1, - ) - annotation_result_storage_directory = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p3beta1/mypy.ini b/owl-bot-staging/v1p3beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1p3beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p3beta1/noxfile.py b/owl-bot-staging/v1p3beta1/noxfile.py deleted file mode 100644 index 0fd4fd5a..00000000 --- a/owl-bot-staging/v1p3beta1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/videointelligence_v1p3beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py b/owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py deleted file mode 100644 index e172e7e2..00000000 --- a/owl-bot-staging/v1p3beta1/scripts/fixup_videointelligence_v1p3beta1_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class videointelligenceCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'annotate_video': ('features', 'input_uri', 'input_content', 'video_context', 'output_uri', 'location_id', ), - 'streaming_annotate_video': ('video_config', 'input_content', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=videointelligenceCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the videointelligence client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1p3beta1/setup.py b/owl-bot-staging/v1p3beta1/setup.py deleted file mode 100644 index 87b7ba3d..00000000 --- a/owl-bot-staging/v1p3beta1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-videointelligence', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1p3beta1/tests/__init__.py b/owl-bot-staging/v1p3beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p3beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/__init__.py b/owl-bot-staging/v1p3beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p3beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p3beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py deleted file mode 100644 index 1205b87d..00000000 --- a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py +++ /dev/null @@ -1,1031 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceAsyncClient -from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service import StreamingVideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service import transports -from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from google.oauth2 import service_account -from google.rpc import status_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None - assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert StreamingVideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - StreamingVideoIntelligenceServiceClient, - StreamingVideoIntelligenceServiceAsyncClient, -]) -def test_streaming_video_intelligence_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), - (transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_streaming_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - StreamingVideoIntelligenceServiceClient, - StreamingVideoIntelligenceServiceAsyncClient, -]) -def test_streaming_video_intelligence_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_streaming_video_intelligence_service_client_get_transport_class(): - transport = StreamingVideoIntelligenceServiceClient.get_transport_class() - available_transports = [ - transports.StreamingVideoIntelligenceServiceGrpcTransport, - ] - assert transport in available_transports - - transport = StreamingVideoIntelligenceServiceClient.get_transport_class("grpc") - assert transport == transports.StreamingVideoIntelligenceServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), - (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(StreamingVideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceClient)) -@mock.patch.object(StreamingVideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceAsyncClient)) -def test_streaming_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(StreamingVideoIntelligenceServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(StreamingVideoIntelligenceServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc", "true"), - (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc", "false"), - (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(StreamingVideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceClient)) -@mock.patch.object(StreamingVideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(StreamingVideoIntelligenceServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_streaming_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), - (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_streaming_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (StreamingVideoIntelligenceServiceClient, transports.StreamingVideoIntelligenceServiceGrpcTransport, "grpc"), - (StreamingVideoIntelligenceServiceAsyncClient, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_streaming_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_streaming_video_intelligence_service_client_client_options_from_dict(): - with mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = StreamingVideoIntelligenceServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_streaming_annotate_video(transport: str = 'grpc', request_type=video_intelligence.StreamingAnnotateVideoRequest): - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([video_intelligence.StreamingAnnotateVideoResponse()]) - response = client.streaming_annotate_video(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, video_intelligence.StreamingAnnotateVideoResponse) - - -def test_streaming_annotate_video_from_dict(): - test_streaming_annotate_video(request_type=dict) - - -@pytest.mark.asyncio -async def test_streaming_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.StreamingAnnotateVideoRequest): - client = StreamingVideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[video_intelligence.StreamingAnnotateVideoResponse()]) - response = await client.streaming_annotate_video(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, video_intelligence.StreamingAnnotateVideoResponse) - - -@pytest.mark.asyncio -async def test_streaming_annotate_video_async_from_dict(): - await test_streaming_annotate_video_async(request_type=dict) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StreamingVideoIntelligenceServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StreamingVideoIntelligenceServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = StreamingVideoIntelligenceServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.StreamingVideoIntelligenceServiceGrpcTransport, - transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.StreamingVideoIntelligenceServiceGrpcTransport, - ) - -def test_streaming_video_intelligence_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.StreamingVideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_streaming_video_intelligence_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.StreamingVideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'streaming_annotate_video', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - -@requires_google_auth_gte_1_25_0 -def test_streaming_video_intelligence_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.StreamingVideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_streaming_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.StreamingVideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_streaming_video_intelligence_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service.transports.StreamingVideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.StreamingVideoIntelligenceServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_streaming_video_intelligence_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - StreamingVideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_streaming_video_intelligence_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - StreamingVideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.StreamingVideoIntelligenceServiceGrpcTransport, - transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_streaming_video_intelligence_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.StreamingVideoIntelligenceServiceGrpcTransport, - transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_streaming_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.StreamingVideoIntelligenceServiceGrpcTransport, grpc_helpers), - (transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_streaming_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "videointelligence.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="videointelligence.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.StreamingVideoIntelligenceServiceGrpcTransport, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_streaming_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_streaming_video_intelligence_service_host_no_port(): - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_streaming_video_intelligence_service_host_with_port(): - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:8000' - -def test_streaming_video_intelligence_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.StreamingVideoIntelligenceServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_streaming_video_intelligence_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.StreamingVideoIntelligenceServiceGrpcTransport, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_streaming_video_intelligence_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.StreamingVideoIntelligenceServiceGrpcTransport, transports.StreamingVideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_streaming_video_intelligence_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = StreamingVideoIntelligenceServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = StreamingVideoIntelligenceServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = StreamingVideoIntelligenceServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = StreamingVideoIntelligenceServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = StreamingVideoIntelligenceServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = StreamingVideoIntelligenceServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = StreamingVideoIntelligenceServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = StreamingVideoIntelligenceServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = StreamingVideoIntelligenceServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = StreamingVideoIntelligenceServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = StreamingVideoIntelligenceServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = StreamingVideoIntelligenceServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = StreamingVideoIntelligenceServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = StreamingVideoIntelligenceServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = StreamingVideoIntelligenceServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.StreamingVideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.StreamingVideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = StreamingVideoIntelligenceServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = StreamingVideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = StreamingVideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py b/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py deleted file mode 100644 index c00d82e2..00000000 --- a/owl-bot-staging/v1p3beta1/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py +++ /dev/null @@ -1,1177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service import VideoIntelligenceServiceAsyncClient -from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service import VideoIntelligenceServiceClient -from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service import transports -from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.videointelligence_v1p3beta1.types import video_intelligence -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(None) is None - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VideoIntelligenceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - VideoIntelligenceServiceClient, - VideoIntelligenceServiceAsyncClient, -]) -def test_video_intelligence_service_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_client_get_transport_class(): - transport = VideoIntelligenceServiceClient.get_transport_class() - available_transports = [ - transports.VideoIntelligenceServiceGrpcTransport, - ] - assert transport in available_transports - - transport = VideoIntelligenceServiceClient.get_transport_class("grpc") - assert transport == transports.VideoIntelligenceServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -def test_video_intelligence_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(VideoIntelligenceServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "true"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc", "false"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VideoIntelligenceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceClient)) -@mock.patch.object(VideoIntelligenceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VideoIntelligenceServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_video_intelligence_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VideoIntelligenceServiceClient, transports.VideoIntelligenceServiceGrpcTransport, "grpc"), - (VideoIntelligenceServiceAsyncClient, transports.VideoIntelligenceServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_video_intelligence_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_video_intelligence_service_client_client_options_from_dict(): - with mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VideoIntelligenceServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_annotate_video(transport: str = 'grpc', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_annotate_video_from_dict(): - test_annotate_video(request_type=dict) - - -def test_annotate_video_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - client.annotate_video() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - -@pytest.mark.asyncio -async def test_annotate_video_async(transport: str = 'grpc_asyncio', request_type=video_intelligence.AnnotateVideoRequest): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.annotate_video(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == video_intelligence.AnnotateVideoRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_annotate_video_async_from_dict(): - await test_annotate_video_async(request_type=dict) - - -def test_annotate_video_flattened(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -def test_annotate_video_flattened_error(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_video), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.annotate_video( - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].input_uri == 'input_uri_value' - assert args[0].features == [video_intelligence.Feature.LABEL_DETECTION] - - -@pytest.mark.asyncio -async def test_annotate_video_flattened_error_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.annotate_video( - video_intelligence.AnnotateVideoRequest(), - input_uri='input_uri_value', - features=[video_intelligence.Feature.LABEL_DETECTION], - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VideoIntelligenceServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VideoIntelligenceServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VideoIntelligenceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VideoIntelligenceServiceGrpcTransport, - ) - -def test_video_intelligence_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_video_intelligence_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VideoIntelligenceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'annotate_video', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_video_intelligence_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service.transports.VideoIntelligenceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VideoIntelligenceServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VideoIntelligenceServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_video_intelligence_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VideoIntelligenceServiceGrpcTransport, - transports.VideoIntelligenceServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_video_intelligence_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VideoIntelligenceServiceGrpcTransport, grpc_helpers), - (transports.VideoIntelligenceServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_video_intelligence_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "videointelligence.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="videointelligence.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_video_intelligence_service_host_no_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:443' - - -def test_video_intelligence_service_host_with_port(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='videointelligence.googleapis.com:8000'), - ) - assert client.transport._host == 'videointelligence.googleapis.com:8000' - -def test_video_intelligence_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_video_intelligence_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VideoIntelligenceServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VideoIntelligenceServiceGrpcTransport, transports.VideoIntelligenceServiceGrpcAsyncIOTransport]) -def test_video_intelligence_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_video_intelligence_service_grpc_lro_client(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_video_intelligence_service_grpc_lro_async_client(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VideoIntelligenceServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = VideoIntelligenceServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = VideoIntelligenceServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = VideoIntelligenceServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VideoIntelligenceServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = VideoIntelligenceServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = VideoIntelligenceServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = VideoIntelligenceServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = VideoIntelligenceServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = VideoIntelligenceServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VideoIntelligenceServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.VideoIntelligenceServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = VideoIntelligenceServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = VideoIntelligenceServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = VideoIntelligenceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() diff --git a/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py b/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py index 8dcc1cc8..ab317273 100644 --- a/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py +++ b/tests/unit/gapic/videointelligence_v1/test_video_intelligence_service.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.videointelligence_v1.services.video_intelligence_service import ( @@ -802,6 +803,9 @@ def test_video_intelligence_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): @@ -1295,3 +1299,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py b/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py index e70020d6..a912f431 100644 --- a/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py +++ b/tests/unit/gapic/videointelligence_v1beta2/test_video_intelligence_service.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.videointelligence_v1beta2.services.video_intelligence_service import ( @@ -802,6 +803,9 @@ def test_video_intelligence_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): @@ -1295,3 +1299,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py b/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py index 976c799d..6d7e3060 100644 --- a/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py +++ b/tests/unit/gapic/videointelligence_v1p1beta1/test_video_intelligence_service.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.videointelligence_v1p1beta1.services.video_intelligence_service import ( @@ -802,6 +803,9 @@ def test_video_intelligence_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): @@ -1295,3 +1299,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py b/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py index 58987fce..7a0470bc 100644 --- a/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py +++ b/tests/unit/gapic/videointelligence_v1p2beta1/test_video_intelligence_service.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.videointelligence_v1p2beta1.services.video_intelligence_service import ( @@ -802,6 +803,9 @@ def test_video_intelligence_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): @@ -1295,3 +1299,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py b/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py index 714b6439..20eb15fa 100644 --- a/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py +++ b/tests/unit/gapic/videointelligence_v1p3beta1/test_streaming_video_intelligence_service.py @@ -29,6 +29,7 @@ from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.videointelligence_v1p3beta1.services.streaming_video_intelligence_service import ( @@ -732,6 +733,9 @@ def test_streaming_video_intelligence_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + @requires_google_auth_gte_1_25_0 def test_streaming_video_intelligence_service_base_transport_with_credentials_file(): @@ -1213,3 +1217,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = StreamingVideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = StreamingVideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() diff --git a/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py b/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py index f20fdab8..e5448040 100644 --- a/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py +++ b/tests/unit/gapic/videointelligence_v1p3beta1/test_video_intelligence_service.py @@ -32,6 +32,7 @@ from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 +from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.videointelligence_v1p3beta1.services.video_intelligence_service import ( @@ -802,6 +803,9 @@ def test_video_intelligence_service_base_transport(): with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() + # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): @@ -1295,3 +1299,49 @@ def test_client_withDEFAULT_CLIENT_INFO(): credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VideoIntelligenceServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = VideoIntelligenceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called()