Code Monkey home page Code Monkey logo

python-vision's Introduction

NOTE:This github repository is archived. The repository contents and history have moved to google-cloud-python.

Python Client for Google Cloud Vision

GA pypi versions

The Google Cloud Vision API enables developers to understand the content of an image by encapsulating powerful machine learning models in an easy to use REST API. It quickly classifies images into thousands of categories (e.g., "sailboat", "lion", "Eiffel Tower"), detects individual objects and faces within images, and finds and reads printed words contained within images. You can build metadata on your image catalog, moderate offensive content, or enable new marketing scenarios through image sentiment analysis. Analyze images uploaded in the request or integrate with your image storage on Google Cloud Storage.

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 Vision API.
  4. Setup Authentication.

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.

Supported Python Versions

Python >= 3.6

Deprecated Python Versions

Python == 2.7.

The last version of this library compatible with Python 2.7 is google-cloud-vision==1.0.0.

RaspberryPi ARM devices

Note: Raspberry Pi ARMv6 is not supported.

Mac/Linux
pip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-vision
Windows
pip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-cloud-vision

Example Usage

from google.cloud import vision

client = vision.ImageAnnotatorClient()
response = client.annotate_image({
  'image': {'source': {'image_uri': 'gs://my-test-bucket/image.jpg'}},
  'features': [{'type_': vision.Feature.Type.FACE_DETECTION}]
})

Known Limitations

Pylint Does Not Work Out Of The Box

Pylint throws errors by default when checking code that uses feature methods on the ImageAnnotatorClient class, such as label_detection() or text_detection().

As a workaround, member checking on all methods of the ImageAnnotatorClient can be disabled using Pylint's generated-members option. To do this on a line-by-line basis, add a comment like # pylint: disable=no-member to suppress this error. To do this for a whole project, you can add the following lines to a .pylintrc file in your project:

[TYPECHECK]

generated-members=<<REGULAR EXPRESSION>>

Substitute a regular expression of your choosing that matches all lines for which you want to disable this error check. For example, if you choose a convention of naming your ImageAnnotatorClient variables image_annotator_client, then your regex could be image_annotator_client.* or something similar.

Next Steps

python-vision's People

Contributors

arithmetic1728 avatar brendanlundy avatar busunkim96 avatar chemelnucfin avatar crwilcox avatar dandhlee avatar danielcressman avatar daspecster avatar dependabot[bot] avatar dhermes avatar dizcology avatar dpebot avatar gcf-owl-bot[bot] avatar google-cloud-policy-bot[bot] avatar kweinmeister avatar lukesneeringer avatar munkhuushmgl avatar nownabe avatar parthea avatar pravindahal avatar release-please[bot] avatar renovate-bot avatar shollyman avatar sid-dinesh94 avatar theacodes avatar tseaver avatar tswast avatar vam-google avatar ylil93 avatar yoshi-automation avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-vision's Issues

google.api_core.exceptions.ServiceUnavailable: 503 Socket closed

I am running 10 containers with the same credentials json which will initialize 10 imageannotatorclient. I am getting this error out of the blue recently. Should I reduce the number of client initializers? Please help. Thanks in advance.
My pip list:

google-cloud-vision 1.0.0
google 2.0.3
google-api-core 1.16.0
google-auth 1.20.0
google-auth-oauthlib 0.4.1
google-cloud 0.34.0
google-cloud-core 1.4.0
google-cloud-storage 1.20.0
google-cloud-vision 1.0.0
google-pasta 0.2.0
google-resumable-media 0.4.1
googleapis-common-protos 1.6.0
grpcio 1.30.0

@busunkim96

Resolve sphinx docs warnings and upgrade sphinx

Recently a change was made in the python client libraries template for noxfile.py to use newer version of sphinx in the nox session that generates the docs. There is code in owlbot.py to use sphinx<3.0.0 which reverts the sphinx upgrade. When I ran nox -s docs with a newer version of sphinx, there were several sphinx warnings. I'll dig into the warnings and propose fixes. The workaround to downgrade sphinx in noxfile.py should be removed in the PR that fixes the warnings.

TextDetectionParams does not support all documented fields

The current definition of the class google.cloud.vision_v1.types.TextDetectionParams does not support all of the parameters that are documented in the Google Cloud Vision API. If possible, it would be good to get the additional parameters supported.

Environment details

  • OS type and version: macOS 10.13.6
  • Python version: 3.9.1
  • pip version: 21.0.1
  • google-cloud-vision version:
Name: google-cloud-vision
Version: 2.3.1
Summary: Cloud Vision API API client library
Home-page: https://github.com/googleapis/python-vision
Author: Google LLC
Author-email: [email protected]
License: Apache 2.0
Location: /usr/local/lib/python3.9/site-packages
Requires: google-api-core, proto-plus
Required-by:

Steps to reproduce

According to the documentation at https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.TextDetectionParams, the TextDetectionParams object has a number of possible field values. However, the corresponding class in the Python package currently (as of 2.3.1) only has enable_text_detection_confidence_score, as can be seen in the documentation at https://googleapis.dev/python/vision/latest/vision_v1/types.html?highlight=textdetection#google.cloud.vision_v1.types.TextDetectionParams and also the source code

Code example

This doesn't seem necessary; the issue is pretty clearly evident from both the API docs and the code itself.

Stack trace

Not relevant.

raise AttributeError(str(ex)) AttributeError: 'DESCRIPTOR' while converting json string to types.AnnotateFileResponse

Environment details

  • OS type and version: linux
  • Python version: 3.7.9
  • pip version: 20.3.3
  • google-cloud-vision version: pip show google-cloud-vision 2.0.0

Code example

# example
from google.protobuf import json_format

json_string = blob.download_as_string()
response = json_format.Parse(json_string, types.AnnotateFileResponse())

Stack trace

parser.ConvertMessage(js_dict, message)
message_descriptor = message.DESCRIPTOR

raise AttributeError(str(ex))
AttributeError: 'DESCRIPTOR'


When I try to convert the json_string to AnnotateFileResponse, I am getting the above error.  I suppose it might be due to the usage of proto-plus as mentioned [here] (https://github.com/googleapis/python-memcache/issues/19#issuecomment-708516816) Can anyone give a possible fix.

How can i set proxy ?

client = vision.ImageAnnotatorClient()
        with io.open(path, 'rb') as image_file:
            content = image_file.read()

        image = vision.types.Image(content=content)

        # response = client.text_detection(image=image)
        response = client.document_text_detection(image=image)

in china ,these network request can't reach.i set proxy in cmd terminal.but i wan't to set proxy in code.how can i do ?

ImageAnnotatorClient throws error on AWS SageMaker notebook: Protocol message FieldDescriptorProto has no "proto3_optional" field.

Environment details

  • OS type and version: SageMaker notebooks: AWS linux 2
  • Python version: Python 3.6.10 :: Anaconda, Inc.
  • pip version: pip 20.0.2
  • google-cloud-vision version: 2.0.0

Steps to reproduce

  1. from google.cloud import vision

Code example

from google.cloud import vision

Stack trace

Screen Shot 2020-10-06 at 11 12 38

~/anaconda3/envs/python3/lib/python3.6/site-packages/google/cloud/vision/__init__.py in <module>
     16 #
     17 
---> 18 from google.cloud.vision_v1.services.image_annotator.async_client import (
     19     ImageAnnotatorAsyncClient,
     20 )

~/anaconda3/envs/python3/lib/python3.6/site-packages/google/cloud/vision_v1/__init__.py in <module>
     19 from google.cloud.vision_helpers import VisionHelpers
     20 
---> 21 from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient
     22 from .services.product_search import ProductSearchClient
     23 from .types.geometry import BoundingPoly

~/anaconda3/envs/python3/lib/python3.6/site-packages/google/cloud/vision_v1/services/image_annotator/__init__.py in <module>
     16 #
     17 
---> 18 from .client import ImageAnnotatorClient
     19 from .async_client import ImageAnnotatorAsyncClient
     20 

~/anaconda3/envs/python3/lib/python3.6/site-packages/google/cloud/vision_v1/services/image_annotator/client.py in <module>
     35 from google.api_core import operation  # type: ignore
     36 from google.api_core import operation_async  # type: ignore
---> 37 from google.cloud.vision_v1.types import image_annotator
     38 
     39 from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO

~/anaconda3/envs/python3/lib/python3.6/site-packages/google/cloud/vision_v1/types/__init__.py in <module>
     16 #
     17 
---> 18 from .geometry import (
     19     Vertex,
     20     NormalizedVertex,

~/anaconda3/envs/python3/lib/python3.6/site-packages/google/cloud/vision_v1/types/geometry.py in <module>
     25 
     26 
---> 27 class Vertex(proto.Message):
     28     r"""A vertex represents a 2D point in the image.
     29     NOTE: the vertex coordinates are in the same scale as the

~/anaconda3/envs/python3/lib/python3.6/site-packages/proto/message.py in __new__(mcls, name, bases, attrs)
    213         desc = descriptor_pb2.DescriptorProto(
    214             name=name,
--> 215             field=[i.descriptor for i in fields],
    216             oneof_decl=[
    217                 descriptor_pb2.OneofDescriptorProto(name=i) for i in oneofs.keys()

~/anaconda3/envs/python3/lib/python3.6/site-packages/proto/message.py in <listcomp>(.0)
    213         desc = descriptor_pb2.DescriptorProto(
    214             name=name,
--> 215             field=[i.descriptor for i in fields],
    216             oneof_decl=[
    217                 descriptor_pb2.OneofDescriptorProto(name=i) for i in oneofs.keys()

~/anaconda3/envs/python3/lib/python3.6/site-packages/proto/fields.py in descriptor(self)
    109                 type_name=type_name,
    110                 json_name=self.json_name,
--> 111                 proto3_optional=self.optional,
    112             )
    113 

ValueError: Protocol message FieldDescriptorProto has no "proto3_optional" field.

Making sure to follow these steps will guarantee the quickest resolution possible.

Thanks!

Synthesis failed for python-vision

Hello! Autosynth couldn't regenerate python-vision. ๐Ÿ’”

Here's the output from running synth.py:

a73/external/gapic_generator_python/requirements.txt (line 4))
  Using cached https://files.pythonhosted.org/packages/30/9e/f663a2aa66a09d838042ae1a2c5659828bb9b41ea3a6efa20a20fd92b121/Jinja2-2.11.2-py2.py3-none-any.whl
  Saved ./Jinja2-2.11.2-py2.py3-none-any.whl
Collecting MarkupSafe==1.1.1 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 5))
  Using cached https://files.pythonhosted.org/packages/b2/5f/23e0023be6bb885d00ffbefad2942bc51a620328ee910f64abe5a8d18dd1/MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
  Saved ./MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
Collecting protobuf==3.13.0 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 6))
  Using cached https://files.pythonhosted.org/packages/30/79/510974552cebff2ba04038544799450defe75e96ea5f1675dbf72cc8744f/protobuf-3.13.0-cp36-cp36m-manylinux1_x86_64.whl
  Saved ./protobuf-3.13.0-cp36-cp36m-manylinux1_x86_64.whl
Collecting pypandoc==1.5 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 7))
  Using cached https://files.pythonhosted.org/packages/d6/b7/5050dc1769c8a93d3ec7c4bd55be161991c94b8b235f88bf7c764449e708/pypandoc-1.5.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmpfs/tmp/tmp4pwoukhh/setuptools-tmp/setuptools/__init__.py", line 6, in <module>
        import distutils.core
      File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/_distutils_hack/__init__.py", line 82, in create_module
        return importlib.import_module('._distutils', 'setuptools')
      File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    ModuleNotFoundError: No module named 'setuptools._distutils'
    
    ----------------------------------------
 (Command "python setup.py egg_info" failed with error code 1 in /tmpfs/tmp/pip-build-ofpnaxze/pypandoc/
)
ERROR: no such package '@gapic_generator_python_pip_deps//': pip_import failed: Collecting click==7.1.2 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 1))
  Using cached https://files.pythonhosted.org/packages/d2/3d/fa76db83bf75c4f8d338c2fd15c8d33fdd7ad23a9b5e57eb6c5de26b430e/click-7.1.2-py2.py3-none-any.whl
  Saved ./click-7.1.2-py2.py3-none-any.whl
Collecting google-api-core==1.22.1 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 2))
  Using cached https://files.pythonhosted.org/packages/e0/2d/7c6c75013105e1d2b6eaa1bf18a56995be1dbc673c38885aea31136e9918/google_api_core-1.22.1-py2.py3-none-any.whl
  Saved ./google_api_core-1.22.1-py2.py3-none-any.whl
Collecting googleapis-common-protos==1.52.0 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 3))
  Using cached https://files.pythonhosted.org/packages/03/74/3956721ea1eb4bcf7502a311fdaa60b85bd751de4e57d1943afe9b334141/googleapis_common_protos-1.52.0-py2.py3-none-any.whl
  Saved ./googleapis_common_protos-1.52.0-py2.py3-none-any.whl
Collecting jinja2==2.11.2 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 4))
  Using cached https://files.pythonhosted.org/packages/30/9e/f663a2aa66a09d838042ae1a2c5659828bb9b41ea3a6efa20a20fd92b121/Jinja2-2.11.2-py2.py3-none-any.whl
  Saved ./Jinja2-2.11.2-py2.py3-none-any.whl
Collecting MarkupSafe==1.1.1 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 5))
  Using cached https://files.pythonhosted.org/packages/b2/5f/23e0023be6bb885d00ffbefad2942bc51a620328ee910f64abe5a8d18dd1/MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
  Saved ./MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
Collecting protobuf==3.13.0 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 6))
  Using cached https://files.pythonhosted.org/packages/30/79/510974552cebff2ba04038544799450defe75e96ea5f1675dbf72cc8744f/protobuf-3.13.0-cp36-cp36m-manylinux1_x86_64.whl
  Saved ./protobuf-3.13.0-cp36-cp36m-manylinux1_x86_64.whl
Collecting pypandoc==1.5 (from -r /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/gapic_generator_python/requirements.txt (line 7))
  Using cached https://files.pythonhosted.org/packages/d6/b7/5050dc1769c8a93d3ec7c4bd55be161991c94b8b235f88bf7c764449e708/pypandoc-1.5.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmpfs/tmp/tmp4pwoukhh/setuptools-tmp/setuptools/__init__.py", line 6, in <module>
        import distutils.core
      File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/_distutils_hack/__init__.py", line 82, in create_module
        return importlib.import_module('._distutils', 'setuptools')
      File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    ModuleNotFoundError: No module named 'setuptools._distutils'
    
    ----------------------------------------
 (Command "python setup.py egg_info" failed with error code 1 in /tmpfs/tmp/pip-build-ofpnaxze/pypandoc/
)
INFO: Elapsed time: 2.186s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (0 packages loaded)
FAILED: Build did NOT complete successfully (0 packages loaded)

Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 102, in <module>
    main()
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 94, in main
    spec.loader.exec_module(synth_module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/kbuilder/.cache/synthtool/python-vision/synth.py", line 33, in <module>
    include_protos=True
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 46, in py_library
    return self._generate_code(service, version, "python", **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 183, in _generate_code
    shell.run(bazel_run_args)
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 39, in run
    raise exc
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 33, in run
    encoding="utf-8",
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 438, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['bazel', '--max_idle_secs=240', 'build', '//google/cloud/vision/v1:vision-v1-py']' returned non-zero exit status 1.
2020-08-31 05:27:30,033 autosynth [ERROR] > Synthesis failed
2020-08-31 05:27:30,033 autosynth [DEBUG] > Running: git reset --hard HEAD
HEAD is now at 81905c4 chore: enable snippet-bot (#39)
2020-08-31 05:27:30,039 autosynth [DEBUG] > Running: git checkout autosynth
Switched to branch 'autosynth'
2020-08-31 05:27:30,044 autosynth [DEBUG] > Running: git clean -fdx
Removing __pycache__/
Removing google/__pycache__/
Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 690, in <module>
    main()
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 539, in main
    return _inner_main(temp_dir)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 670, in _inner_main
    commit_count = synthesize_loop(x, multiple_prs, change_pusher, synthesizer)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 375, in synthesize_loop
    has_changes = toolbox.synthesize_version_in_new_branch(synthesizer, youngest)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 273, in synthesize_version_in_new_branch
    synthesizer.synthesize(synth_log_path, self.environ)
  File "/tmpfs/src/github/synthtool/autosynth/synthesizer.py", line 120, in synthesize
    synth_proc.check_returncode()  # Raise an exception.
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 389, in check_returncode
    self.stderr)
subprocess.CalledProcessError: Command '['/tmpfs/src/github/synthtool/env/bin/python3', '-m', 'synthtool', '--metadata', 'synth.metadata', 'synth.py', '--']' returned non-zero exit status 1.

Google internal developers can see the full log here.

Issue in migrating to google-cloud-vision 2.0

Hello,
Greetings for the day.

I am trying to run this code with google-cloud-vision 2.0 but it gives me error. This code worked well with previous versions.

from google.cloud import vision_v1p4beta1 as vision
from google.oauth2 import service_account
import io

client = vision.ImageAnnotatorClient(credentials=credentials)


with io.open("temp.jpg", 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)
image_context = vision.ImageContext(language_hints=["en"])

response = client.annotate_image({'image': image,
                                  'image_context': image_context,
                                  'features': [{'type': vision.Feature.Type.DOCUMENT_TEXT_DETECTION, 'model': 'builtin/legacy_20190601'}], })

Error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-a12bdee22ec3> in <module>
     27 image_context = vision.ImageContext(language_hints=["en"])
     28 
---> 29 response = client.annotate_image({'image': image,
     30                                   'image_context': image_context,
     31                                   'features': [{'type': vision.Feature.Type.DOCUMENT_TEXT_DETECTION, 'model': 'builtin/legacy_20190601'}], })

~/miniconda3/envs/idp3/lib/python3.8/site-packages/google/cloud/vision_helpers/__init__.py in annotate_image(self, request, retry, timeout, metadata)
     74         elif len(request.features) == 0:
     75             request.features = self._get_all_features()
---> 76         r = self.batch_annotate_images(
     77             requests=[request], retry=retry, timeout=timeout, metadata=metadata
     78         )

~/miniconda3/envs/idp3/lib/python3.8/site-packages/google/cloud/vision_v1p4beta1/services/image_annotator/client.py in batch_annotate_images(self, request, requests, retry, timeout, metadata)
    306             if requests is not None:
    307                 for i in range(len(requests)):
--> 308                     requests[i] = image_annotator.AnnotateImageRequest(requests[i])
    309 
    310             # If we have keyword arguments corresponding to fields on the

~/miniconda3/envs/idp3/lib/python3.8/site-packages/proto/message.py in __init__(self, mapping, **kwargs)
    424         for key, value in mapping.items():
    425             pb_type = self._meta.fields[key].pb_type
--> 426             pb_value = marshal.to_proto(pb_type, value)
    427             if pb_value is not None:
    428                 params[key] = pb_value

~/miniconda3/envs/idp3/lib/python3.8/site-packages/proto/marshal/marshal.py in to_proto(self, proto_type, value, strict)
    184             # Convert lists and tuples recursively.
    185             if isinstance(value, (list, tuple)):
--> 186                 return type(value)(self.to_proto(proto_type, i) for i in value)
    187 
    188         # Convert dictionaries recursively when the proto type is a map.

~/miniconda3/envs/idp3/lib/python3.8/site-packages/proto/marshal/marshal.py in <genexpr>(.0)
    184             # Convert lists and tuples recursively.
    185             if isinstance(value, (list, tuple)):
--> 186                 return type(value)(self.to_proto(proto_type, i) for i in value)
    187 
    188         # Convert dictionaries recursively when the proto type is a map.

~/miniconda3/envs/idp3/lib/python3.8/site-packages/proto/marshal/marshal.py in to_proto(self, proto_type, value, strict)
    203         # Convert ordinary values.
    204         rule = self._rules.get(proto_type, self._noop)
--> 205         pb_value = rule.to_proto(value)
    206 
    207         # Sanity check: If we are in strict mode, did we get the value we want?

~/miniconda3/envs/idp3/lib/python3.8/site-packages/proto/marshal/rules/message.py in to_proto(self, value)
     30             return self._wrapper.pb(value)
     31         if isinstance(value, dict) and not self.is_map:
---> 32             return self._descriptor(**value)
     33         return value
     34 

ValueError: Protocol message Feature has no "type" field.

Please kindly help me in resolving this issue.

Vision: custom vocabulary in vision ocr (handwritten text)

I would like to pass the keywords that i expect to be present in the image as an argument to document_text_detection. Just as you can pass the context to speech to text, it would be useful to have something like that here as well.

Synthesis failed for python-vision

Hello! Autosynth couldn't regenerate python-vision. ๐Ÿ’”

Here's the output from running synth.py:

Cloning into 'working_repo'...
Switched to branch 'autosynth'
Running synthtool
['/tmpfs/src/git/autosynth/env/bin/python3', '-m', 'synthtool', 'synth.py', '--']
synthtool > Executing /tmpfs/src/git/autosynth/working_repo/synth.py.
On branch autosynth
nothing to commit, working tree clean
HEAD detached at FETCH_HEAD
nothing to commit, working tree clean
synthtool > Ensuring dependencies.
synthtool > Pulling artman image.
latest: Pulling from googleapis/artman
Digest: sha256:6aec9c34db0e4be221cdaf6faba27bdc07cfea846808b3d3b964dfce3a9a0f9b
Status: Image is up to date for googleapis/artman:latest
synthtool > Cloning googleapis.
synthtool > Running generator for google/cloud/vision/artman_vision_v1.yaml.
synthtool > Generated code into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1.
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1/web_detection.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1/google/cloud/vision_v1/proto/web_detection.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1/image_annotator.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1/google/cloud/vision_v1/proto/image_annotator.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1/product_search.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1/google/cloud/vision_v1/proto/product_search.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1/product_search_service.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1/google/cloud/vision_v1/proto/product_search_service.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1/geometry.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1/google/cloud/vision_v1/proto/geometry.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1/text_annotation.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1/google/cloud/vision_v1/proto/text_annotation.proto
synthtool > Placed proto files into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1/google/cloud/vision_v1/proto.
synthtool > Replaced 'from __future__ import absolute_import' in google/cloud/vision_v1/__init__.py.
synthtool > Replaced 'image_annotator_client' in google/cloud/vision_v1/__init__.py.
synthtool > Replaced 'from google.cloud.vision_v1.gapic import iac' in google/cloud/vision_v1/__init__.py.
synthtool > Replaced 'class ImageAnnotatorClient\\(iac.ImageAnnotatorClient\\):' in google/cloud/vision_v1/__init__.py.
synthtool > Running generator for google/cloud/vision/artman_vision_v1p1beta1.yaml.
synthtool > Generated code into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p1beta1.
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p1beta1/web_detection.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p1beta1/google/cloud/vision_v1p1beta1/proto/web_detection.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p1beta1/image_annotator.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p1beta1/google/cloud/vision_v1p1beta1/proto/image_annotator.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p1beta1/geometry.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p1beta1/google/cloud/vision_v1p1beta1/proto/geometry.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p1beta1/text_annotation.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p1beta1/google/cloud/vision_v1p1beta1/proto/text_annotation.proto
synthtool > Placed proto files into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p1beta1/google/cloud/vision_v1p1beta1/proto.
synthtool > Replaced 'from __future__ import absolute_import' in google/cloud/vision_v1p1beta1/__init__.py.
synthtool > Replaced 'image_annotator_client' in google/cloud/vision_v1p1beta1/__init__.py.
synthtool > Replaced 'from google.cloud.vision_v1p1beta1.gapic import iac' in google/cloud/vision_v1p1beta1/__init__.py.
synthtool > Replaced 'class ImageAnnotatorClient\\(iac.ImageAnnotatorClient\\):' in google/cloud/vision_v1p1beta1/__init__.py.
synthtool > Running generator for google/cloud/vision/artman_vision_v1p2beta1.yaml.
synthtool > Generated code into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p2beta1.
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p2beta1/web_detection.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p2beta1/google/cloud/vision_v1p2beta1/proto/web_detection.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p2beta1/image_annotator.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p2beta1/google/cloud/vision_v1p2beta1/proto/image_annotator.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p2beta1/geometry.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p2beta1/google/cloud/vision_v1p2beta1/proto/geometry.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p2beta1/text_annotation.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p2beta1/google/cloud/vision_v1p2beta1/proto/text_annotation.proto
synthtool > Placed proto files into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p2beta1/google/cloud/vision_v1p2beta1/proto.
synthtool > Replaced 'from __future__ import absolute_import' in google/cloud/vision_v1p2beta1/__init__.py.
synthtool > Replaced 'image_annotator_client' in google/cloud/vision_v1p2beta1/__init__.py.
synthtool > Replaced 'from google.cloud.vision_v1p2beta1.gapic import iac' in google/cloud/vision_v1p2beta1/__init__.py.
synthtool > Replaced 'class ImageAnnotatorClient\\(iac.ImageAnnotatorClient\\):' in google/cloud/vision_v1p2beta1/__init__.py.
synthtool > Running generator for google/cloud/vision/artman_vision_v1p3beta1.yaml.
synthtool > Generated code into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1.
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p3beta1/web_detection.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1/google/cloud/vision_v1p3beta1/proto/web_detection.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p3beta1/image_annotator.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1/google/cloud/vision_v1p3beta1/proto/image_annotator.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p3beta1/product_search.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1/google/cloud/vision_v1p3beta1/proto/product_search.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p3beta1/product_search_service.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1/google/cloud/vision_v1p3beta1/proto/product_search_service.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p3beta1/geometry.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1/google/cloud/vision_v1p3beta1/proto/geometry.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p3beta1/text_annotation.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1/google/cloud/vision_v1p3beta1/proto/text_annotation.proto
synthtool > Placed proto files into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p3beta1/google/cloud/vision_v1p3beta1/proto.
synthtool > Replaced 'from __future__ import absolute_import' in google/cloud/vision_v1p3beta1/__init__.py.
synthtool > Replaced 'image_annotator_client' in google/cloud/vision_v1p3beta1/__init__.py.
synthtool > Replaced 'from google.cloud.vision_v1p3beta1.gapic import iac' in google/cloud/vision_v1p3beta1/__init__.py.
synthtool > Replaced 'class ImageAnnotatorClient\\(iac.ImageAnnotatorClient\\):' in google/cloud/vision_v1p3beta1/__init__.py.
synthtool > Running generator for google/cloud/vision/artman_vision_v1p4beta1.yaml.
synthtool > Generated code into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1.
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p4beta1/web_detection.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto/web_detection.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p4beta1/face.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto/face.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p4beta1/image_annotator.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto/image_annotator.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p4beta1/product_search.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto/product_search.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p4beta1/product_search_service.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto/product_search_service.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p4beta1/geometry.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto/geometry.proto
synthtool > Copy: /home/kbuilder/.cache/synthtool/googleapis/google/cloud/vision/v1p4beta1/text_annotation.proto to /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto/text_annotation.proto
synthtool > Placed proto files into /home/kbuilder/.cache/synthtool/googleapis/artman-genfiles/python/vision-v1p4beta1/google/cloud/vision_v1p4beta1/proto.
synthtool > Replaced 'from __future__ import absolute_import' in google/cloud/vision_v1p4beta1/__init__.py.
synthtool > Replaced 'image_annotator_client' in google/cloud/vision_v1p4beta1/__init__.py.
synthtool > Replaced 'from google.cloud.vision_v1p4beta1.gapic import iac' in google/cloud/vision_v1p4beta1/__init__.py.
synthtool > Replaced 'class ImageAnnotatorClient\\(iac.ImageAnnotatorClient\\):' in google/cloud/vision_v1p4beta1/__init__.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p2beta1/gapic/image_annotator_client.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p2beta1/gapic/transports/image_annotator_grpc_transport.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p3beta1/gapic/product_search_client.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p3beta1/gapic/image_annotator_client.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p3beta1/gapic/transports/image_annotator_grpc_transport.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p3beta1/gapic/transports/product_search_grpc_transport.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1/gapic/product_search_client.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1/gapic/image_annotator_client.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1/gapic/transports/image_annotator_grpc_transport.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1/gapic/transports/product_search_grpc_transport.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p4beta1/gapic/product_search_client.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p4beta1/gapic/image_annotator_client.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p4beta1/gapic/transports/image_annotator_grpc_transport.py.
synthtool > Replaced 'import google.api_core.operations_v1' in google/cloud/vision_v1p4beta1/gapic/transports/product_search_grpc_transport.py.
.coveragerc
.flake8
.github/CONTRIBUTING.md
.github/ISSUE_TEMPLATE/bug_report.md
.github/ISSUE_TEMPLATE/feature_request.md
.github/ISSUE_TEMPLATE/support_request.md
.github/PULL_REQUEST_TEMPLATE.md
.github/release-please.yml
.gitignore
.kokoro/build.sh
.kokoro/continuous/common.cfg
.kokoro/continuous/continuous.cfg
.kokoro/docs/common.cfg
.kokoro/docs/docs.cfg
.kokoro/presubmit/common.cfg
.kokoro/presubmit/presubmit.cfg
.kokoro/publish-docs.sh
.kokoro/release.sh
.kokoro/release/common.cfg
.kokoro/release/release.cfg
.kokoro/trampoline.sh
CODE_OF_CONDUCT.md
CONTRIBUTING.rst
LICENSE
MANIFEST.in
docs/_static/custom.css
docs/_templates/layout.html
docs/conf.py.j2
noxfile.py.j2
renovate.json
setup.cfg
Running session blacken
Creating virtual environment (virtualenv) using python3.6 in .nox/blacken
pip install black==19.3b0
Error: pip is not installed into the virtualenv, it is located at /tmpfs/src/git/autosynth/env/bin/pip. Pass external=True into run() to explicitly allow this.
Session blacken failed.
synthtool > Failed executing nox -s blacken:

None
synthtool > Wrote metadata to synth.metadata.
Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.1/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.1/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/synthtool/__main__.py", line 102, in <module>
    main()
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/synthtool/__main__.py", line 94, in main
    spec.loader.exec_module(synth_module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "/tmpfs/src/git/autosynth/working_repo/synth.py", line 87, in <module>
    s.shell.run(["nox", "-s", "blacken"], hide_output=False)
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/synthtool/shell.py", line 39, in run
    raise exc
  File "/tmpfs/src/git/autosynth/env/lib/python3.6/site-packages/synthtool/shell.py", line 33, in run
    encoding="utf-8",
  File "/home/kbuilder/.pyenv/versions/3.6.1/lib/python3.6/subprocess.py", line 418, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['nox', '-s', 'blacken']' returned non-zero exit status 1.

Synthesis failed

Google internal developers can see the full log here.

Synthesis failed for python-vision

Hello! Autosynth couldn't regenerate python-vision. ๐Ÿ’”

Please investigate and fix this issue within 5 business days. While it remains broken,
this library cannot be updated with changes to the python-vision API, and the library grows
stale.

See https://github.com/googleapis/synthtool/blob/master/autosynth/TroubleShooting.md
for trouble shooting tips.

Here's the output from running synth.py:

lder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:77:1
DEBUG: Rule 'com_google_protoc_java_resource_names_plugin' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "4b714b35ee04ba90f560ee60e64c7357428efcb6b0f3a298f343f8ec2c6d4a5d"
DEBUG: Call stack for the definition of repository 'com_google_protoc_java_resource_names_plugin' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:234:1
DEBUG: Rule 'protoc_docs_plugin' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "33b387245455775e0de45869c7355cc5a9e98b396a6fc43b02812a63b75fee20"
DEBUG: Call stack for the definition of repository 'protoc_docs_plugin' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:258:1
DEBUG: Rule 'rules_python' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "48f7e716f4098b85296ad93f5a133baf712968c13fbc2fdf3a6136158fe86eac"
DEBUG: Call stack for the definition of repository 'rules_python' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:42:1
DEBUG: Rule 'gapic_generator_python' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "fe995def6873fcbdc2a8764ef4bce96eb971a9d1950fe9db9be442f3c64fb3b6"
DEBUG: Call stack for the definition of repository 'gapic_generator_python' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:278:1
DEBUG: Rule 'com_googleapis_gapic_generator_go' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "c0d0efba86429cee5e52baf838165b0ed7cafae1748d025abec109d25e006628"
DEBUG: Call stack for the definition of repository 'com_googleapis_gapic_generator_go' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:300:1
DEBUG: Rule 'gapic_generator_php' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "3dffc5c34a5f35666843df04b42d6ce1c545b992f9c093a777ec40833b548d86"
DEBUG: Call stack for the definition of repository 'gapic_generator_php' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:364:1
DEBUG: Rule 'gapic_generator_csharp' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "4db430cfb9293e4521ec8e8138f8095faf035d8e752cf332d227710d749939eb"
DEBUG: Call stack for the definition of repository 'gapic_generator_csharp' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:386:1
DEBUG: Rule 'gapic_generator_ruby' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "a14ec475388542f2ea70d16d75579065758acc4b99fdd6d59463d54e1a9e4499"
DEBUG: Call stack for the definition of repository 'gapic_generator_ruby' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:400:1
DEBUG: /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/rules_python/python/pip.bzl:61:5: DEPRECATED: the pip_repositories rule has been replaced with pip_install, please see rules_python 0.1 release notes
DEBUG: Rule 'bazel_skylib' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "1dde365491125a3db70731e25658dfdd3bc5dbdfd11b840b3e987ecf043c7ca0"
DEBUG: Call stack for the definition of repository 'bazel_skylib' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:35:1
Analyzing: target //google/cloud/vision/v1:vision-v1-py (1 packages loaded, 0 targets configured)
ERROR: /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/upb/bazel/upb_proto_library.bzl:257:29: aspect() got unexpected keyword argument 'incompatible_use_toolchain_transition'
ERROR: Analysis of target '//google/cloud/vision/v1:vision-v1-py' failed; build aborted: error loading package '@com_github_grpc_grpc//': in /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/com_github_grpc_grpc/bazel/grpc_build_system.bzl: Extension file 'bazel/upb_proto_library.bzl' has errors
INFO: Elapsed time: 0.278s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (3 packages loaded, 1 target configured)
FAILED: Build did NOT complete successfully (3 packages loaded, 1 target configured)

Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 102, in <module>
    main()
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 94, in main
    spec.loader.exec_module(synth_module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/kbuilder/.cache/synthtool/python-vision/synth.py", line 34, in <module>
    include_protos=True
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 52, in py_library
    return self._generate_code(service, version, "python", False, **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 204, in _generate_code
    shell.run(bazel_run_args)
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 39, in run
    raise exc
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 33, in run
    encoding="utf-8",
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 438, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['bazel', '--max_idle_secs=240', 'build', '//google/cloud/vision/v1:vision-v1-py']' returned non-zero exit status 1.
2021-04-27 02:18:05,454 autosynth [ERROR] > Synthesis failed
2021-04-27 02:18:05,454 autosynth [DEBUG] > Running: git reset --hard HEAD
HEAD is now at 5f55c74 chore(revert): revert preventing normalization (#139)
2021-04-27 02:18:05,460 autosynth [DEBUG] > Running: git checkout autosynth
Switched to branch 'autosynth'
2021-04-27 02:18:05,466 autosynth [DEBUG] > Running: git clean -fdx
Removing __pycache__/
Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 356, in <module>
    main()
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 191, in main
    return _inner_main(temp_dir)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 336, in _inner_main
    commit_count = synthesize_loop(x, multiple_prs, change_pusher, synthesizer)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 68, in synthesize_loop
    has_changes = toolbox.synthesize_version_in_new_branch(synthesizer, youngest)
  File "/tmpfs/src/github/synthtool/autosynth/synth_toolbox.py", line 259, in synthesize_version_in_new_branch
    synthesizer.synthesize(synth_log_path, self.environ)
  File "/tmpfs/src/github/synthtool/autosynth/synthesizer.py", line 120, in synthesize
    synth_proc.check_returncode()  # Raise an exception.
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 389, in check_returncode
    self.stderr)
subprocess.CalledProcessError: Command '['/tmpfs/src/github/synthtool/env/bin/python3', '-m', 'synthtool', '--metadata', 'synth.metadata', 'synth.py', '--']' returned non-zero exit status 1.

Google internal developers can see the full log here.

google.api_core.exceptions.ServiceUnavailable: 503 Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT Signature.', '{"error":"invalid_grant","error_description":"Invalid JWT Signature."}')

google-api-core 1.17.0
google-auth 1.14.1
google-cloud-vision 1.0.0
python 3.6.9
and my os is ubuntu 18.04
i am trying to extract text from images
while i am running this code

`import` os, io
from google.cloud import vision
import pandas as pd
from google.oauth2 import service_account
credentials = service_account.Credentials. from_service_account_file('silver-catwalk-276005-0d6c98a26db3.json')
client = vision.ImageAnnotatorClient(credentials=credentials)
file_name = 'img0.jpg'  
image_path = f'/home/apiiit-rkv/Desktop/Task, I CAN/codes/{file_name}'

with io.open(image_path, 'rb') as image_file:
    content = image_file.read()
image = vision.types.Image(content=content)
response = client.text_detection(image=image)  # returns TextAnnotation
df = pd.DataFrame(columns=['locale', 'description'])
texts = response.text_annotations
for text in texts:
    df = df.append(
        dict(
            locale=text.locale,
            description=text.description
        ),
        ignore_index=True
    )
print(df['description'][0])

it throwing this error

Traceback (most recent call last):
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
   return callable_(*args, **kwargs)
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/grpc/_channel.py", line 826, in __call__
   return _end_unary_response_blocking(state, call, False, None)
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
   raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
   status = StatusCode.UNAVAILABLE
   details = "Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT Signature.', '{"error":"invalid_grant","error_description":"Invalid JWT Signature."}')"
   debug_error_string = "{"created":"@1588564948.414167046","description":"Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT Signature.', '{"error":"invalid_grant","error_description":"Invalid JWT Signature."}')","file":"src/core/lib/security/credentials/plugin/plugin_credentials.cc","file_line":79,"grpc_status":14}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "first_project_googleVision.py", line 30, in <module>
   response = client.text_detection(image=image)  # returns TextAnnotation
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/google/cloud/vision_helpers/decorators.py", line 101, in inner
   response = self.annotate_image(request, retry=retry, timeout=timeout)
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/google/cloud/vision_helpers/__init__.py", line 72, in annotate_image
   r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/google/cloud/vision_v1/gapic/image_annotator_client.py", line 274, in batch_annotate_images
   request, retry=retry, timeout=timeout, metadata=metadata
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
   return wrapped_func(*args, **kwargs)
 File "/home/apiiit-rkv/.local/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
   six.raise_from(exceptions.from_grpc_error(exc), exc)
 File "<string>", line 3, in raise_from
google.api_core.exceptions.ServiceUnavailable: 503 Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT Signature.', '{"error":"invalid_grant","error_description":"Invalid JWT Signature."}')

please help me to solve this error

The build failed

This test failed!

To configure my behavior, see the Flaky Bot documentation.

If I'm commenting on this issue too often, add the flakybot: quiet label and
I will stop commenting.


commit: 898d9db
buildURL: Build Status, Sponge
status: failed

Test output
vision_async_batch_annotate_images_test.py:26: in 
    BUCKET = os.environ["CLOUD_STORAGE_BUCKET"]
/usr/local/lib/python3.6/os.py:669: in __getitem__
    raise KeyError(key) from None
E   KeyError: 'CLOUD_STORAGE_BUCKET'

Pickling a AnnotateImageResponse is no longer possible?

Environment details

  • OS type and version: MacOS 10.15.7
  • Python version: 3.7.5
  • pip version: pip --version
  • google-cloud-vision version: 2.0.0

Code example

client = vision.ImageAnnotatorClient()
 The name of the image file to annotate
file_name = os.path.abspath('some_file')

# use the stable model as the new one that will be rolled out soon,
# might break things
features = [
    vision.Feature(type_=vision.Feature.Type.LABEL_DETECTION, model="builtin/stable"),
]

with open(file_name, 'rb') as image_file:
        content = image_file.read()

image = vision.Image(content=content)

response = client.annotate_image(request={
    'image': image,
    'features': features}, retry=retry.Retry(deadline=3))

# trying to pickle or dill will fail:
import pickle
with io.open("thing.pickle", 'wb') as f:
    pickle.dump(response,f )

Stack trace

*** _pickle.PicklingError: Can't pickle <class 'AnnotateImageResponse'>: attribute lookup AnnotateImageResponse on __main__ failed

We are using pickle to pickle a response from Cloud Vision API and put it into a local cache to process images faster.
The new 2.0.0 seems to break this functionality. I found this workaround on SF, but it means we will loose all our previous cache information.

Import Error (Vision API) 'ImportError: cannot import name 'types' from 'google.cloud.vision'

I'm trying to run the Vision API on my Mac (Text Editor VSCode) but I always get the same Error: ImportError: cannot import name 'types' from 'google.cloud.vision' (Full Screenshot attached)

I tried the following fixes:

  • I ran several versions of python in a venv (it was active)
  • I installed several versions of the google-cloud-vision (v0, 1.0.0, 2.0.0)
  • I checked several times if my venv was contamined by running this code

mkdir test cd test python3 -m venv venv source venv/bin/activate pip install google-cloud-vision python3 -c "from google.cloud import vision; print(vision.__name__)" google.cloud.vision_

I will also post my installed packages
aiohttp==3.6.2 async-timeout==3.0.1 attrs==20.2.0 cachetools==4.1.1 certifi==2020.6.20 chardet==3.0.4 google-api-core==1.22.2 google-auth==1.22.0 google-cloud-vision==2.0.0 googleapis-common-protos==1.52.0 grpcio==1.32.0 idna==2.10 libcst==0.3.12 multidict==4.7.6 mypy-extensions==0.4.3 proto-plus==1.10.0 protobuf==3.13.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 rsa==4.6 six==1.15.0 typing-extensions==3.7.4.3 typing-inspect==0.6.0 urllib3==1.25.10 yarl==1.6.0

I will appreciate any help.

Bildschirmfoto 2020-10-02 um 11 39 56

AutoML Vision: Apple CoreML Version of the classifier does not output a label - Solution?

PLEASE READ: If you have a support contract with Google, please create an issue in the support console instead of filing on GitHub. This will ensure a timely response.

Good evening,

For the past few months I have been using Google AutoML Vision to train different Machine Learning Classifiers to perform Single-Label classification. At the moment I am experimenting with those models in order to deploy them in an iOS application.

For every different model I downloaded the CoreML version and tried to run inference on them. For the first one, generated on the 9th of April 2020 everything went smoothly and I was able to run inference on the model and obtain the labels as well as the the confidence.

However, for every other model things became very complicated. I was not getting a label anymore and I only got back a MultiArray (Float32) that (I think) contains the confidence for every different label.

"MultiArray : Float32 1 x 58 matrix
[2.218795e-23,0,0,0,0,0,0,3.239883e-33,0,7.783418e-31,0,2.907443e-37,4.699545e-27,5.825165e-27,7.421043e-38,3.183992e-31,0,0,0,6.888631e-15,0,4.317692e-37,0,0,5.699229e-16,0,5.271491e-30,0,0,0,0,0,0,2.180327e-13,0,2.245058e-10,0,1.466715e-05,0,0,0,9.004483e-05,0,0,0,0,3.859872e-29,7.121189e-24,0.6383881,1.217046e-10,0,0,0,0,0.3615072,0,0,2.544428e-35]" (1.000000)

After experimenting a lot and always getting the same results I opened the .mlmodel in Netron and found out that the models, despite being CoreML files and trained using the same settings had different specifications.

For the first model I used these are the properties:

format: Core ML v1
type: Neural Network Classifier
input: image_0 - image<RGB,224x224>
output: (scores_0 - map<string,float64>, classLabel - string)

Properties for every other model generated in Google AutoML Vision:

format: Core ML v4
type: Neural Network
input: image_0 - float32[1,224,224,3]
output: float32

However all the model were generated the same way.

Screen Shot 2020-09-20 at 00 26 29

I want to use the CoreML models in my application but I can't figure out how to change the output type of the models. I have read the coremltools documentation and tried to implement it but I can't figure it out. My ideia is to change the spec and load the classification labels.

Thank you!

Screen Shot 2020-09-20 at 00 24 08
Screen Shot 2020-09-20 at 00 24 17

face_detection returns empty response while label_detection works

Over the last two days I am trying out the face_detection feature of the ImageAnnotatorClient. It always returns an empty list. You can see in the attached picture that it indeed contains a face.
I then checked the label_detection method and this works perfectly and returns a full response. I also tried to send a request using annotate_image directly using the vision.enums.Feature.Type.FACE_DETECTION feature and get the same result: an empty list.
Finally I checked the Vision API online and dropped the image there. This works and the face is recognized in a frame as a person.
So, why is it not working in the python-vision library? I checked the code and found in the decorators.pyfile that the special feature methods are added on the fly to the ImageAnnotatorClient. Could it be that something there goes wrong?

I am working on AI Platform Notebooks using a TensorFlow 2.2 Notebook without GPUs.

Here the code I use:

def detect_face(file, max_results=4):
    """Find a face in an image and return its coordinates"""
    client = vision.ImageAnnotatorClient()
    content = file.read()
    image = types.Image(content=content)
    
    # Return the face coordinates
    return client.face_detection(image=image, max_results=max_results).face_annotations

Here the code used with label_detection (this works):

with open('test_image.png', 'rb') as img:
    client = vision.ImageAnnotatorClient()
    content = img.read()
    image = types.Image(content=content)
    
    ret = client.label_detection(image=image)
    ret

And here the example using annotate_image directly with the FACE_DETECTION feature:

from google.cloud import vision
from base64 import b64encode
with open('test_image.png', 'rb') as img:
    client = vision.ImageAnnotatorClient()
    content = img.read()
    image = types.Image(content=content)
    
    ret = client.annotate_image({
        'image': {'content': b64encode(content)},
        'features': [{'type': vision.enums.Feature.Type.FACE_DETECTION}],
    })
    ret

I appreciate your work.
test_image

Works well in local host but not live in production

Environment details

  • OS type and version: Mac Catalina
  • google-cloud-vision version: 2.1.0

Steps to reproduce

I have my django vision app working just well in Dev localhost. But when I deploy it to google cloudrun, the vision API always returns this error: Product matching query does not exist.
Screen Shot 2021-02-13 at 10 27 40 AM

But the same query through localhost, returns vision API match:

Screen Shot 2021-02-13 at 10 25 11 AM

Here is the query code:

'''
     search for images - products
    '''
    @staticmethod
    def get_similar_products_file(product_set_id, product_category, file_path, filter):
        """Search similar products to image.
        Args:
            project_id: Id of the project.
            location: A compute region name.
            product_set_id: Id of the product set.
            product_category: Category of the product.
            file_path: Local file path of the image to be searched.
            filter: Condition to be applied on the labels.
            Example for filter: (color = red OR color = blue) AND style = kids
            It will search on all products with the following labels:
            color:red AND style:kids
            color:blue AND style:kids
        """
        try:
            # product_search_client is needed only for its helper methods.
            product_search_client = vision.ProductSearchClient()
            image_annotator_client = vision.ImageAnnotatorClient()

            # # Read the image as a stream of bytes.
            # with open(file_path, 'rb') as image_file:
            #     content = image_file.read()
            
            # # Create annotate image request along with product search feature.
            # image = vision.Image(content=content)

             # Create annotate image request along with product search feature.
            image_source = vision.ImageSource(image_uri=f'gs://bucket-app.appspot.com/search-images/{file_path}')
            image = vision.Image(source=image_source)

            # product search specific parameters
            product_set_path = product_search_client.product_set_path(
                project=MarketplaceHelpers.project_id, location=MarketplaceHelpers.location,
                product_set=product_set_id)
            product_search_params = vision.ProductSearchParams(
                product_set=product_set_path,
                product_categories=[product_category])  # ,filter=filter
            image_context = vision.ImageContext(
                product_search_params=product_search_params)

            # Search products similar to the image.
            response = image_annotator_client.product_search(
                image, image_context=image_context)

            # print(response)

            index_time = response.product_search_results.index_time
            print('Product set index time: ')
            print(index_time)

            results = response.product_search_results.results

            # print('Search results:')
            # for result in results:
            #     product = result.product

            #     print('Score(Confidence): {}'.format(result.score))
            #     print('Image name: {}'.format(result.image))

            #     print('Product name: {}'.format(product.name))
            #     print('Product display name: {}'.format(
            #         product.display_name))
            #     print('Product description: {}\n'.format(product.description))
            #     print('Product labels: {}\n'.format(product.product_labels))
            return results
        except Exception as e:
            print('VISION_API_GET_SIMILAR_PRODUCTS: {}'.format(e))
            logging.error('VISION_API_GET_SIMILAR_PRODUCTS: {}'.format(e))

My question then is, what is different, what am I missing for the implementation to work on a live server?

Error google.api_core.exceptions.InternalServerError: 500 Internal Error

google-api-core 1.23.0
grpcio 1.31.0
google-cloud-vision 2.0.0

Hello, we are using the offline (asynchronous) batch requests to send a lot of images of old newspapers (containing a lot of text) to the Vision API using the cloud vision lib for Python 3.

We are sending now 500 images per batch, each of those processing the document_text and face_detect features, using builtin/latest model. As we have millions of images to process, we try to send like 10 batches or more in parallel, so we look closely to our quota of "Async image annotation number of images in processing" (which for us, is currently '20,000').

The issue is, a lot of InternalServerError: 500 Internal Error is occurring, and the biggest problem is it seems it's not a mapped error, so Vision outputs this error, charges against our billing and then make a retry, sometimes it works, sometimes it will give a second retry and charges us again, so we end up with a very unpleasant billing.

Maybe it's related to LRO similar to this issue issue

Stack trace sample (raw)

Traceback (most recent call last):
File "/code/src/job/main.py", line 47, in main
vision.handle()
File "/code/src/job/vision.py", line 386, in handle
result = vision.async_annotate(
File "/usr/lib/python3.8/site-packages/assetcloud/api/vision.py", line 246, in async_annotate
result = operation.result(timeout=timeout)
File "/usr/lib/python3.8/site-packages/google/api_core/future/polling.py", line 134, in result
raise self._exception
File "/usr/lib/python3.8/site-packages/assetcloud/api/vision.py", line 246, in async_annotate
result = operation.result(timeout=timeout)
File "/usr/lib/python3.8/site-packages/google/api_core/future/polling.py", line 134, in result
raise self._exception
File "/usr/lib/python3.8/site-packages/assetcloud/api/vision.py", line 246, in async_annotate
result = operation.result(timeout=timeout)
File "/usr/lib/python3.8/site-packages/google/api_core/future/polling.py", line 134, in result
raise self._exception
google.api_core.exceptions.InternalServerError: 500 Internal Error.

Attached our python code, the abstraction and one newspaper page sample

vision.txt
async_annotate.txt

sample

convert api response to json

accessing vision api using this code

client = vision.ImageAnnotatorClient() response = client.annotate_image({ 'image': {'source': {'filename': image}}, })

response type is
google.cloud.vision_v1.types.image_annotator.AnnotateImageResponse

i cant convert it to json neither can iterate it

any suggestion on how t convert it to json so i can iterate it

Synthesis failed for python-vision

Hello! Autosynth couldn't regenerate python-vision. ๐Ÿ’”

Here's the output from running synth.py:

uct_search.proto -Igoogle/cloud/vision/v1/product_search_service.proto=google/cloud/vision/v1/product_search_service.proto -Igoogle/cloud/vision/v1/text_annotation.proto=google/cloud/vision/v1/text_annotation.proto -Igoogle/cloud/vision/v1/web_detection.proto=google/cloud/vision/v1/web_detection.proto -Igoogle/api/annotations.proto=google/api/annotations.proto -Igoogle/api/http.proto=google/api/http.proto -Igoogle/protobuf/descriptor.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/descriptor_proto/google/protobuf/descriptor.proto -Igoogle/api/client.proto=google/api/client.proto -Igoogle/api/field_behavior.proto=google/api/field_behavior.proto -Igoogle/api/resource.proto=google/api/resource.proto -Igoogle/longrunning/operations.proto=google/longrunning/operations.proto -Igoogle/rpc/status.proto=google/rpc/status.proto -Igoogle/protobuf/any.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/any_proto/google/protobuf/any.proto -Igoogle/protobuf/duration.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/duration_proto/google/protobuf/duration.proto -Igoogle/protobuf/empty.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/empty_proto/google/protobuf/empty.proto -Igoogle/type/color.proto=google/type/color.proto -Igoogle/protobuf/wrappers.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/wrappers_proto/google/protobuf/wrappers.proto -Igoogle/type/latlng.proto=google/type/latlng.proto -Igoogle/protobuf/field_mask.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/field_mask_proto/google/protobuf/field_mask.proto -Igoogle/protobuf/timestamp.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/timestamp_proto/google/protobuf/timestamp.proto google/cloud/vision/v1/geometry.proto google/cloud/vision/v1/image_annotator.proto google/cloud/vision/v1/product_search.proto google/cloud/vision/v1/product_search_service.proto google/cloud/vision/v1/text_annotation.proto google/cloud/vision/v1/web_detection.proto` failed (Exit 1) protoc failed: error executing command bazel-out/host/bin/external/com_google_protobuf/protoc --experimental_allow_proto3_optional '--plugin=protoc-gen-python_gapic=bazel-out/host/bin/external/gapic_generator_python/gapic_plugin' ... (remaining 29 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox
google/cloud/vision/v1/geometry.proto:20:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/product_search.proto:23:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/text_annotation.proto:21:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/web_detection.proto:20:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/image_annotator.proto:28:1: warning: Import google/protobuf/field_mask.proto is unused.
Traceback (most recent call last):
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/cli/generate_with_pandoc.py", line 3, in <module>
    from gapic.cli import generate
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/cli/generate.py", line 23, in <module>
    from gapic import generator
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/generator/__init__.py", line 21, in <module>
    from .generator import Generator
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/generator/generator.py", line 24, in <module>
    from gapic.samplegen import manifest, samplegen
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/samplegen/__init__.py", line 15, in <module>
    from gapic.samplegen import samplegen
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/samplegen/samplegen.py", line 27, in <module>
    from gapic.schema import wrappers
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/schema/__init__.py", line 23, in <module>
    from gapic.schema.api import API
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/52/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/schema/api.py", line 29, in <module>
    from google.api_core import exceptions  # type: ignore
ModuleNotFoundError: No module named 'google.api_core'
--python_gapic_out: protoc-gen-python_gapic: Plugin failed with status code 1.
Target //google/cloud/vision/v1:vision-v1-py failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 1.148s, Critical Path: 0.85s
INFO: 0 processes.
FAILED: Build did NOT complete successfully
FAILED: Build did NOT complete successfully

Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 102, in <module>
    main()
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 94, in main
    spec.loader.exec_module(synth_module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/kbuilder/.cache/synthtool/python-vision/synth.py", line 34, in <module>
    include_protos=True
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 52, in py_library
    return self._generate_code(service, version, "python", **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 197, in _generate_code
    shell.run(bazel_run_args)
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 39, in run
    raise exc
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 33, in run
    encoding="utf-8",
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 438, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['bazel', '--max_idle_secs=240', 'build', '//google/cloud/vision/v1:vision-v1-py']' returned non-zero exit status 1.
2021-01-28 05:49:41,816 autosynth [ERROR] > Synthesis failed
2021-01-28 05:49:41,816 autosynth [DEBUG] > Running: git reset --hard HEAD
HEAD is now at 79c5dd6 chore: release 2.1.0 (#84)
2021-01-28 05:49:41,823 autosynth [DEBUG] > Running: git checkout autosynth
Switched to branch 'autosynth'
2021-01-28 05:49:41,829 autosynth [DEBUG] > Running: git clean -fdx
Removing __pycache__/
Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 354, in <module>
    main()
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 189, in main
    return _inner_main(temp_dir)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 334, in _inner_main
    commit_count = synthesize_loop(x, multiple_prs, change_pusher, synthesizer)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 65, in synthesize_loop
    has_changes = toolbox.synthesize_version_in_new_branch(synthesizer, youngest)
  File "/tmpfs/src/github/synthtool/autosynth/synth_toolbox.py", line 259, in synthesize_version_in_new_branch
    synthesizer.synthesize(synth_log_path, self.environ)
  File "/tmpfs/src/github/synthtool/autosynth/synthesizer.py", line 120, in synthesize
    synth_proc.check_returncode()  # Raise an exception.
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 389, in check_returncode
    self.stderr)
subprocess.CalledProcessError: Command '['/tmpfs/src/github/synthtool/env/bin/python3', '-m', 'synthtool', '--metadata', 'synth.metadata', 'synth.py', '--']' returned non-zero exit status 1.

Google internal developers can see the full log here.

ImageAnnotatorClient.text_detection retry bug!

Thanks for stopping by to let us know something could be better!

PLEASE READ: If you have a support contract with Google, please create an issue in the support console instead of filing on GitHub. This will ensure a timely response.

Please run down the following list and make sure you've tried the usual "quick fixes":

If you are still having issues, please be sure to include as much information as possible:

Environment details

  • OS type and version: Arch Linux
  • Python version: 3.8.3
  • pip version: 20.1.1
  • google-cloud-vision version: 1.0.0

Steps to reproduce

  1. Try to call `ImageAnnotatorClient.text_detection(image, retry=5)
  2. Get error that int object is not callable. Something somewhere is doing retry()

Code example

See here

from google.cloud import vision
from google.cloud.vision import types
from google.oauth2 import service_account

class Image:
	
	def __init__(self, service_file, image_content=None, image_uri=None):
		self.google = vision.ImageAnnotatorClient(credentials=service_account.Credentials.from_service_account_file(
			service_file))
		
		self.image = types.Image()
		if image_content:
			self.image.content = image_content
		elif image_uri:
			self.image.source.image_uri = image_uri
		else:
			raise AttributeError('Please define either image_uri or image_content')
	
	def get_text(self):
		print("Requesting TEXT_DETECTION from Google Cloud API. This will cost us 0.0015 USD.")
		response = self.google.text_detection(image=self.image, retry=5)
		self.text_found = response.text_annotations

Stack trace

_________ test_answer[dutch_xp-https://cdn.discordapp.com/attachments/370708840850653184/726727557453447238/Screenshot_20200628-111544_Pokmon_GO.jpg-224399847] _________

test_name = 'dutch_xp', input = 'https://cdn.discordapp.com/attachments/370708840850653184/726727557453447238/Screenshot_20200628-111544_Pokmon_GO.jpg'
expected = 224399847

    @pytest.mark.parametrize("test_name,input,expected", options)
    def test_answer(test_name,input,expected):
>       assert func(input) == expected

test_profileself_total_xp.py:27: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
test_profileself_total_xp.py:6: in func
    foo.get_text()
PogoOCR/types.py:92: in get_text
    super().get_text()
PogoOCR/cloudvision.py:21: in get_text
    response = self.google.text_detection(image=self.image, retry=5)
env/lib/python3.8/site-packages/google/cloud/vision_helpers/decorators.py:101: in inner
    response = self.annotate_image(request, retry=retry, timeout=timeout)
env/lib/python3.8/site-packages/google/cloud/vision_helpers/__init__.py:72: in annotate_image
    r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
env/lib/python3.8/site-packages/google/cloud/vision_v1/gapic/image_annotator_client.py:273: in batch_annotate_images
    return self._inner_api_calls["batch_annotate_images"](
env/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py:130: in __call__
    wrapped_func = _apply_decorators(self._target, [retry, timeout_])
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

func = <function _wrap_unary_errors.<locals>.error_remapped_callable at 0x7f12e75ee040>, decorators = <filter object at 0x7f12e75b6460>

    def _apply_decorators(func, decorators):
        """Apply a list of decorators to a given function.
    
        ``decorators`` may contain items that are ``None`` or ``False`` which will
        be ignored.
        """
        decorators = filter(_is_not_none_or_false, reversed(decorators))
    
        for decorator in decorators:
>           func = decorator(func)
E           TypeError: 'int' object is not callable

env/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py:45: TypeError

Making sure to follow these steps will guarantee the quickest resolution possible.

Thanks!

P.S Your docs are unreadable.

AttributeError: partially initialized module 'google.cloud.vision' has no attribute 'ImageAnnotatorClient' (most likely due to a circular import)

I just installed google-cloud-vision via conda using the following command
conda install google-cloud-vision
and I'm Getting the above error

Environment details

  • OS type and version:
  • Python version: 3.8.5
  • conda version: conda install google-cloud-vision
  • google-cloud-vision version: 0.42.0

Steps to reproduce

python x.py

Code example

x.py

from google.cloud import vision
client = vision.ImageAnnotatorClient()

AttributeError: module 'google.cloud.vision' has no attribute 'ImageAnnotatorClient'

Polling and fetching status of an async request

Hi

The following snippet in the examples works for OCR on a large pdf file using the Async API.

# [START vision_text_detection_pdf_gcs]
def async_detect_document(gcs_source_uri, gcs_destination_uri):
    """OCR with PDF/TIFF as source files on GCS"""
    import json
    import re
    from google.cloud import vision
    from google.cloud import storage

    # Supported mime_types are: 'application/pdf' and 'image/tiff'
    mime_type = 'application/pdf'

    # How many pages should be grouped into each json output file.
    batch_size = 2

    client = vision.ImageAnnotatorClient()

    feature = vision.Feature(
        type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION)

    gcs_source = vision.GcsSource(uri=gcs_source_uri)
    input_config = vision.InputConfig(
        gcs_source=gcs_source, mime_type=mime_type)

    gcs_destination = vision.GcsDestination(uri=gcs_destination_uri)
    output_config = vision.OutputConfig(
        gcs_destination=gcs_destination, batch_size=batch_size)

    async_request = vision.AsyncAnnotateFileRequest(
        features=[feature], input_config=input_config,
        output_config=output_config)

    operation = client.async_batch_annotate_files(
        requests=[async_request])

    print('Waiting for the operation to finish.')
    operation.result(timeout=420)

    # Once the request has completed and the output has been
    # written to GCS, we can list all the output files.
    storage_client = storage.Client()

    match = re.match(r'gs://([^/]+)/(.+)', gcs_destination_uri)
    bucket_name = match.group(1)
    prefix = match.group(2)

    bucket = storage_client.get_bucket(bucket_name)

    # List objects with the given prefix.
    blob_list = list(bucket.list_blobs(prefix=prefix))
    print('Output files:')
    for blob in blob_list:
        print(blob.name)

    # Process the first output file from GCS.
    # Since we specified batch_size=2, the first response contains
    # the first two pages of the input file.
    output = blob_list[0]

    json_string = output.download_as_string()
    response = json.loads(json_string)

    # The actual response for the first page of the input file.
    first_page_response = response['responses'][0]
    annotation = first_page_response['fullTextAnnotation']

    # Here we print the full text from the first page.
    # The response contains more information:
    # annotation/pages/blocks/paragraphs/words/symbols
    # including confidence scores and bounding boxes
    print('Full text:\n')
    print(annotation['text'])
# [END vision_text_detection_pdf_gcs]

How do I poll the status of the async operation. Although I could find some info regarding this here, help regarding the implementation would be appreciated.

Thanks

samples.snippets.detect.detect_test: test_detect_web_with_geo failed

This test failed!

To configure my behavior, see the Flaky Bot documentation.

If I'm commenting on this issue too often, add the flakybot: quiet label and
I will stop commenting.


commit: 4a26166
buildURL: Build Status, Sponge
status: failed

Test output
args = (requests {
  image {
    content: "\377\330\377\341?\376Exif\000\000MM\000*\000\000\000\010\000\013\001\017\000\002\0...   type_: WEB_DETECTION
  }
  image_context {
    web_detection_params {
      include_geo_results: true
    }
  }
}
,)
kwargs = {'metadata': [('x-goog-api-client', 'gl-python/3.6.13 grpc/1.38.1 gax/1.31.0 gapic/2.4.0')]}
@six.wraps(callable_)
def error_remapped_callable(*args, **kwargs):
    try:
      return callable_(*args, **kwargs)

.nox/py-3-6/lib/python3.6/site-packages/google/api_core/grpc_helpers.py:67:


self = <grpc._channel.UnaryUnaryMultiCallable object at 0x7fb18c383cf8>
request = requests {
image {
content: "\377\330\377\341?\376Exif\000\000MM\000*\000\000\000\010\000\013\001\017\000\002\00...
type
: WEB_DETECTION
}
image_context {
web_detection_params {
include_geo_results: true
}
}
}

timeout = None
metadata = [('x-goog-api-client', 'gl-python/3.6.13 grpc/1.38.1 gax/1.31.0 gapic/2.4.0')]
credentials = None, wait_for_ready = None, compression = None

def __call__(self,
             request,
             timeout=None,
             metadata=None,
             credentials=None,
             wait_for_ready=None,
             compression=None):
    state, call, = self._blocking(request, timeout, metadata, credentials,
                                  wait_for_ready, compression)
  return _end_unary_response_blocking(state, call, False, None)

.nox/py-3-6/lib/python3.6/site-packages/grpc/_channel.py:946:


state = <grpc._channel._RPCState object at 0x7fb18c23a518>
call = <grpc._cython.cygrpc.SegregatedCall object at 0x7fb18c240b08>
with_call = False, deadline = None

def _end_unary_response_blocking(state, call, with_call, deadline):
    if state.code is grpc.StatusCode.OK:
        if with_call:
            rendezvous = _MultiThreadedRendezvous(state, call, None, deadline)
            return state.response, rendezvous
        else:
            return state.response
    else:
      raise _InactiveRpcError(state)

E grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
E status = StatusCode.UNAUTHENTICATED
E details = "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
E debug_error_string = "{"created":"@1626167042.296343632","description":"Error received from peer ipv4:74.125.142.95:443","file":"src/core/lib/surface/call.cc","file_line":1066,"grpc_message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","grpc_status":16}"
E >

.nox/py-3-6/lib/python3.6/site-packages/grpc/_channel.py:849: _InactiveRpcError

The above exception was the direct cause of the following exception:

capsys = <_pytest.capture.CaptureFixture object at 0x7fb18c27e128>

def test_detect_web_with_geo(capsys):
    file_name = os.path.join(
        os.path.dirname(__file__),
        'resources/city.jpg')

    @backoff.on_exception(
        backoff.expo, Exception, max_time=60, giveup=only_sample_error)
    def run_sample():
        detect.web_entities_include_geo_results(file_name)
  run_sample()

detect_test.py:194:


.nox/py-3-6/lib/python3.6/site-packages/backoff/_sync.py:94: in retry
ret = target(*args, **kwargs)
detect_test.py:192: in run_sample
detect.web_entities_include_geo_results(file_name)
detect.py:613: in web_entities_include_geo_results
response = client.web_detection(image=image, image_context=image_context)
../../../google/cloud/vision_helpers/decorators.py:113: in inner
request, retry=retry, timeout=timeout, metadata=metadata
../../../google/cloud/vision_helpers/init.py:77: in annotate_image
requests=[request], retry=retry, timeout=timeout, metadata=metadata
../../../google/cloud/vision_v1/services/image_annotator/client.py:434: in batch_annotate_images
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
.nox/py-3-6/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py:145: in call
return wrapped_func(*args, **kwargs)
.nox/py-3-6/lib/python3.6/site-packages/google/api_core/grpc_helpers.py:69: in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)


value = None
from_value = <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAUTHENTICATED
details = "Request had invalid a...entication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","grpc_status":16}"

???
E google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

:3: Unauthenticated

async batch processing API not allowing publicly-accessible image HTTP/HTTPS URL

Apparently the ImageSource attribute of vision requests should allow "A publicly-accessible image HTTP/HTTPS URL"
https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Image
https://googleapis.dev/python/vision/latest/vision_v1/types.html

Here, the Google API core seems to only expect a google storage uri link

Environment details

  • OS type and version: macOS Big Sur 11.0.1
  • Python version: 3.9.1`
  • pip version: 20.3.3
  • google-cloud-vision version: 2.0.0

Code example

from google.cloud import vision
client = vision.ImageAnnotatorClient()

requests = []
labels = []
# I had an array of image urls in a json file, but using the same url over and over gives the same error
images = range(100)
for img in images:
    source = {"image_uri": "https://images.unsplash.com/photo-1544845120-288673aefccc?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9"}
    image = {"source": source}
    features = [
        {"type_": vision.Feature.Type.LABEL_DETECTION}
    ]
    requests.append({"image": image, "features": features})

# The max number of responses to output in each JSON file
batch_size = 2  # max batch size
gcs_destination = {"uri": "gs://imagesort/results/"}
output_config = {"gcs_destination": gcs_destination,
                 "batch_size": batch_size}

operation = client.async_batch_annotate_images(
    requests=requests, output_config=output_config)

print("Waiting for operation to complete...")
response = operation.result(90)

Stack trace

Traceback (most recent call last):
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/grpc/_channel.py", line 923, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/grpc/_channel.py", line 826, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
	status = StatusCode.INVALID_ARGUMENT
	details = "Invalid gcs prefix provided in request image.source.image_uri field. Valid prefixes must start with 'gs://'."
	debug_error_string = "{"created":"@1611278568.485631000","description":"Error received from peer ipv6:[2404:6800:4015:800::200a]:443","file":"src/core/lib/surface/call.cc","file_line":1068,"grpc_message":"Invalid gcs prefix provided in request image.source.image_uri field. Valid prefixes must start with 'gs://'.","grpc_status":3}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/georgeoconnor/imagesort/test.py", line 22, in <module>
    operation = client.async_batch_annotate_images(
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/google/cloud/vision_v1/services/image_annotator/client.py", line 493, in async_batch_annotate_images
    response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
    return wrapped_func(*args, **kwargs)
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/google/api_core/retry.py", line 281, in retry_wrapped_func
    return retry_target(
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/google/api_core/retry.py", line 184, in retry_target
    return target()
  File "/Users/georgeoconnor/imagesort/env/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Invalid gcs prefix provided in request image.source.image_uri field. Valid prefixes must start with 'gs://'.

Asynch calls of the vision api

I was wondering how the calls can be made asynchronous without using the batch functionality? (with something like asyncio)

samples.snippets.detect.detect_test: test_async_detect_document failed

This test failed!

To configure my behavior, see the Build Cop Bot documentation.

If I'm commenting on this issue too often, add the buildcop: quiet label and
I will stop commenting.


commit: ab25338
buildURL: Build Status, Sponge
status: failed

Test output
target = functools.partial(>)
predicate = .if_exception_type_predicate at 0x7f791c1f3840>
sleep_generator = 
deadline = 420, on_error = None
def retry_target(target, predicate, sleep_generator, deadline, on_error=None):
    """Call a function and retry if it fails.

    This is the lowest-level retry helper. Generally, you'll use the
    higher-level retry helper :class:`Retry`.

    Args:
        target(Callable): The function to call and retry. This must be a
            nullary function - apply arguments with `functools.partial`.
        predicate (Callable[Exception]): A callable used to determine if an
            exception raised by the target should be considered retryable.
            It should return True to retry or False otherwise.
        sleep_generator (Iterable[float]): An infinite iterator that determines
            how long to sleep between retries.
        deadline (float): How long to keep retrying the target. The last sleep
            period is shortened as necessary, so that the last retry runs at
            ``deadline`` (and not considerably beyond it).
        on_error (Callable[Exception]): A function to call while processing a
            retryable exception.  Any error raised by this function will *not*
            be caught.

    Returns:
        Any: the return value of the target function.

    Raises:
        google.api_core.RetryError: If the deadline is exceeded while retrying.
        ValueError: If the sleep generator stops yielding values.
        Exception: If the target raises a method that isn't retryable.
    """
    if deadline is not None:
        deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta(
            seconds=deadline
        )
    else:
        deadline_datetime = None

    last_exc = None

    for sleep in sleep_generator:
        try:
          return target()

.nox/py-3-6/lib/python3.6/site-packages/google/api_core/retry.py:184:


self = <google.api_core.operation.Operation object at 0x7f791973a7b8>
retry = <google.api_core.retry.Retry object at 0x7f791c179e80>

def _done_or_raise(self, retry=DEFAULT_RETRY):
    """Check if the future is done and raise if it's not."""
    kwargs = {} if retry is DEFAULT_RETRY else {"retry": retry}

    if not self.done(**kwargs):
      raise _OperationNotComplete()

E google.api_core.future.polling._OperationNotComplete

.nox/py-3-6/lib/python3.6/site-packages/google/api_core/future/polling.py:86: _OperationNotComplete

The above exception was the direct cause of the following exception:

self = <google.api_core.operation.Operation object at 0x7f791973a7b8>
timeout = 420, retry = <google.api_core.retry.Retry object at 0x7f791c179e80>

def _blocking_poll(self, timeout=None, retry=DEFAULT_RETRY):
    """Poll and wait for the Future to be resolved.

    Args:
        timeout (int):
            How long (in seconds) to wait for the operation to complete.
            If None, wait indefinitely.
    """
    if self._result_set:
        return

    retry_ = self._retry.with_deadline(timeout)

    try:
        kwargs = {} if retry is DEFAULT_RETRY else {"retry": retry}
      retry_(self._done_or_raise)(**kwargs)

.nox/py-3-6/lib/python3.6/site-packages/google/api_core/future/polling.py:107:


args = (), kwargs = {}
target = functools.partial(<bound method PollingFuture._done_or_raise of <google.api_core.operation.Operation object at 0x7f791973a7b8>>)
sleep_generator = <generator object exponential_sleep_generator at 0x7f79196a2468>

@general_helpers.wraps(func)
def retry_wrapped_func(*args, **kwargs):
    """A wrapper that calls target function with retry."""
    target = functools.partial(func, *args, **kwargs)
    sleep_generator = exponential_sleep_generator(
        self._initial, self._maximum, multiplier=self._multiplier
    )
    return retry_target(
        target,
        self._predicate,
        sleep_generator,
        self._deadline,
      on_error=on_error,
    )

.nox/py-3-6/lib/python3.6/site-packages/google/api_core/retry.py:286:


target = functools.partial(<bound method PollingFuture._done_or_raise of <google.api_core.operation.Operation object at 0x7f791973a7b8>>)
predicate = <function if_exception_type..if_exception_type_predicate at 0x7f791c1f3840>
sleep_generator = <generator object exponential_sleep_generator at 0x7f79196a2468>
deadline = 420, on_error = None

def retry_target(target, predicate, sleep_generator, deadline, on_error=None):
    """Call a function and retry if it fails.

    This is the lowest-level retry helper. Generally, you'll use the
    higher-level retry helper :class:`Retry`.

    Args:
        target(Callable): The function to call and retry. This must be a
            nullary function - apply arguments with `functools.partial`.
        predicate (Callable[Exception]): A callable used to determine if an
            exception raised by the target should be considered retryable.
            It should return True to retry or False otherwise.
        sleep_generator (Iterable[float]): An infinite iterator that determines
            how long to sleep between retries.
        deadline (float): How long to keep retrying the target. The last sleep
            period is shortened as necessary, so that the last retry runs at
            ``deadline`` (and not considerably beyond it).
        on_error (Callable[Exception]): A function to call while processing a
            retryable exception.  Any error raised by this function will *not*
            be caught.

    Returns:
        Any: the return value of the target function.

    Raises:
        google.api_core.RetryError: If the deadline is exceeded while retrying.
        ValueError: If the sleep generator stops yielding values.
        Exception: If the target raises a method that isn't retryable.
    """
    if deadline is not None:
        deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta(
            seconds=deadline
        )
    else:
        deadline_datetime = None

    last_exc = None

    for sleep in sleep_generator:
        try:
            return target()

        # pylint: disable=broad-except
        # This function explicitly must deal with broad exceptions.
        except Exception as exc:
            if not predicate(exc):
                raise
            last_exc = exc
            if on_error is not None:
                on_error(exc)

        now = datetime_helpers.utcnow()

        if deadline_datetime is not None:
            if deadline_datetime <= now:
                six.raise_from(
                    exceptions.RetryError(
                        "Deadline of {:.1f}s exceeded while calling {}".format(
                            deadline, target
                        ),
                        last_exc,
                    ),
                  last_exc,
                )

.nox/py-3-6/lib/python3.6/site-packages/google/api_core/retry.py:206:


value = None, from_value = _OperationNotComplete()

???
E google.api_core.exceptions.RetryError: Deadline of 420.0s exceeded while calling functools.partial(<bound method PollingFuture._done_or_raise of <google.api_core.operation.Operation object at 0x7f791973a7b8>>), last exception:

:3: RetryError

During handling of the above exception, another exception occurred:

capsys = <_pytest.capture.CaptureFixture object at 0x7f79196a8a20>

def test_async_detect_document(capsys):
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(BUCKET)
    if len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) > 0:
        for blob in bucket.list_blobs(prefix=OUTPUT_PREFIX):
            blob.delete()

    assert len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) == 0

    uri = 'gs://{}/vision/document/custom_0773375000_title_only.pdf'.format(
        ASSET_BUCKET)
    detect.async_detect_document(
        gcs_source_uri=uri,
      gcs_destination_uri=GCS_DESTINATION_URI)

detect_test.py:258:


detect.py:840: in async_detect_document
operation.result(timeout=420)
.nox/py-3-6/lib/python3.6/site-packages/google/api_core/future/polling.py:129: in result
self._blocking_poll(timeout=timeout, **kwargs)


self = <google.api_core.operation.Operation object at 0x7f791973a7b8>
timeout = 420, retry = <google.api_core.retry.Retry object at 0x7f791c179e80>

def _blocking_poll(self, timeout=None, retry=DEFAULT_RETRY):
    """Poll and wait for the Future to be resolved.

    Args:
        timeout (int):
            How long (in seconds) to wait for the operation to complete.
            If None, wait indefinitely.
    """
    if self._result_set:
        return

    retry_ = self._retry.with_deadline(timeout)

    try:
        kwargs = {} if retry is DEFAULT_RETRY else {"retry": retry}
        retry_(self._done_or_raise)(**kwargs)
    except exceptions.RetryError:
        raise concurrent.futures.TimeoutError(
          "Operation did not complete within the designated " "timeout."
        )

E concurrent.futures._base.TimeoutError: Operation did not complete within the designated timeout.

.nox/py-3-6/lib/python3.6/site-packages/google/api_core/future/polling.py:110: TimeoutError

Google cloud vision does not work behind proxy and self-managed SSL

Issue

Now I am using google cloud (behind proxy) vision to detect text in the image.

Environment variables

export HTTP_PROXY="http://username:[email protected]:8080"
export HTTPS_PROXY="http://username:[email protected]:8080"
export REQUESTS_CA_BUNDLE=/home/test/certificate.cer
export SSL_CERT_FILE=/home/test/certificate.cer

My code

os.environ['GOOGLE_APPLICATION_CREDENTIALS']='./json.json'
def google_ocr(image_file):
    try:
        # Instantiates a client
        client = vision.ImageAnnotatorClient()

        # Loads the image into memory
        with io.open(image_file, 'rb') as image_file:
            content = image_file.read()

        image = types.Image(content=content)

        # Performs label detection on the image file
        response = client.text_detection(image=image,
                                         image_context={"language_hints": ["en"]},)

        annotations = response.text_annotations
        if len(annotations) > 0:
            text = annotations[0].description
        else:
            text = ''

        print(text)

        return text
    except Exception as e:
        print(e)
        raise Exception

image = "./IMG.PNG"

print(google_ocr(image))

But there following error:

D0904 17:14:26.604910755   25602 ev_posix.cc:175]            Using polling engine: epollex
D0904 17:14:26.604977752   25602 lb_policy_registry.cc:40]   registering LB policy factory for "grpclb"
D0904 17:14:26.604984805   25602 lb_policy_registry.cc:40]   registering LB policy factory for "cds_experimental"
D0904 17:14:26.604992289   25602 lb_policy_registry.cc:40]   registering LB policy factory for "eds_experimental"
D0904 17:14:26.604996046   25602 lb_policy_registry.cc:40]   registering LB policy factory for "lrs_experimental"
D0904 17:14:26.604999302   25602 lb_policy_registry.cc:40]   registering LB policy factory for "priority_experimental"
D0904 17:14:26.605002428   25602 lb_policy_registry.cc:40]   registering LB policy factory for "weighted_target_experimental"
D0904 17:14:26.605006536   25602 lb_policy_registry.cc:40]   registering LB policy factory for "xds_routing_experimental"
D0904 17:14:26.605008991   25602 lb_policy_registry.cc:40]   registering LB policy factory for "pick_first"
D0904 17:14:26.605012417   25602 lb_policy_registry.cc:40]   registering LB policy factory for "round_robin"
D0904 17:14:26.605014902   25602 dns_resolver_ares.cc:507]   Using ares dns resolver
I0904 17:14:46.652944635   25632 subchannel.cc:1033]         Connect failed: {"created":"@1599214486.652892116","description":"Failed to connect to remote host: FD Shutdown","file":"src/core/lib/iomgr/lockfree_event.cc","file_line":195,"os_error":"Timeout occurred","referenced_errors":[{"created":"@1599214486.652880073","description":"connect() timed out","file":"src/core/lib/iomgr/tcp_client_posix.cc","file_line":113}],"target_address":"ipv4:172.217.26.138:443"}
I0904 17:14:46.653047319   25632 subchannel.cc:1033]         Connect failed: {"created":"@1599214486.653027010","description":"Network is unreachable","errno":101,"file":"src/core/lib/iomgr/tcp_client_posix.cc","file_line":296,"os_error":"Network is unreachable","syscall":"connect","target_address":"ipv6:[2404:6800:4005:808::200a]:443"}
I0904 17:14:46.653062938   25632 subchannel.cc:970]          Subchannel 0x1636680: Retry immediately
I0904 17:14:46.653069190   25632 subchannel.cc:997]          Failed to connect to channel, retrying
503 failed to connect to all addresses
Traceback (most recent call last):
  File "/home/atom_test/.local/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/home/atom_test/.local/lib/python3.6/site-packages/grpc/_channel.py", line 826, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/home/atom_test/.local/lib/python3.6/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
	status = StatusCode.UNAVAILABLE
	details = "failed to connect to all addresses"
	debug_error_string = "{"created":"@1599214486.653060353","description":"Failed to pick subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":4090,"referenced_errors":[{"created":"@1599214486.653058420","description":"failed to connect to all addresses","file":"src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc","file_line":394,"grpc_status":14}]}"

Here is network package capture

17:14:26.654152 IP System-Product-Name.51852 > hkg12s21-in-f10.1e100.net.https: Flags [S], seq 2069919229, win 64240, options [mss 1460,sackOK,TS val 2735503221 ecr 0,nop,wscale 7], length 0
17:14:27.667848 IP System-Product-Name.51852 > hkg12s21-in-f10.1e100.net.https: Flags [S], seq 2069919229, win 64240, options [mss 1460,sackOK,TS val 2735504235 ecr 0,nop,wscale 7], length 0
17:14:29.683836 IP System-Product-Name.51852 > hkg12s21-in-f10.1e100.net.https: Flags [S], seq 2069919229, win 64240, options [mss 1460,sackOK,TS val 2735506251 ecr 0,nop,wscale 7], length 0
17:14:33.811859 IP System-Product-Name.51852 > hkg12s21-in-f10.1e100.net.https: Flags [S], seq 2069919229, win 64240, options [mss 1460,sackOK,TS val 2735510379 ecr 0,nop,wscale 7], length 0
17:14:42.004065 IP System-Product-Name.51852 > hkg12s21-in-f10.1e100.net.https: Flags [S], seq 2069919229, win 64240, options [mss 1460,sackOK,TS val 2735518571 ecr 0,nop,wscale 7], length 0
17:14:46.653117 IP System-Product-Name.52098 > hkg12s21-in-f10.1e100.net.https: Flags [S], seq 3739133444, win 64240, options [mss 1460,sackOK,TS val 2735523220 ecr 0,nop,wscale 7], length 0

The oauth2.googleapis.com was redirect to hkg12s21-in-f10.1e100.net
When I am using curl with the certificate, it can connect to the host hkg12s21-in-f10.1e100.net. Just with python code, it does not work.

test@System-Product-Name:~$ curl --request POST https://hkg12s21-in-f10.1e100.net --cacert /home/test/certificate.cer
<!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>404.</b> <ins>Thatโ€™s an error.</ins>
  <p>The requested URL <code>/</code> was not found on this server.  <ins>Thatโ€™s all we know.</ins>

TextDetectionParams does not contain disable_orientation_detection parameter

`def async_detect_document(gcs_source_uri, gcs_destination_uri):
"""OCR with PDF/TIFF as source files on GCS"""

# Supported mime_types are: 'application/pdf' and 'image/tiff'
mime_type = "application/pdf"

# How many pages should be grouped into each json output file.
batch_size = 10

client = vision.ImageAnnotatorClient()

text_feature = vision.Feature(type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION)

image_context = vision.ImageContext(
    text_detection_params=vision.TextDetectionParams(disable_orientation_detection=True)
)
features = [text_feature]

gcs_source = vision.GcsSource(uri=gcs_source_uri)
input_config = vision.InputConfig(gcs_source=gcs_source, mime_type=mime_type)

gcs_destination = vision.GcsDestination(uri=gcs_destination_uri)
output_config = vision.OutputConfig(gcs_destination=gcs_destination, batch_size=batch_size)

async_request = vision.AsyncAnnotateFileRequest(
    features=features,
    image_context=image_context,
    input_config=input_config,
    output_config=output_config,
)`

image_context = vision.ImageContext( text_detection_params=vision.TextDetectionParams(disable_orientation_detection=True) )

I get the following error, because of the line above.
`Traceback (most recent call last):
File ".\spike\google_ocr.py", line 84, in
"gs://manan-ocr-testing/tt",
File ".\spike\google_ocr.py", line 24, in async_detect_document
text_detection_params=vision.TextDetectionParams(mapping={"lineFilter": {"paths": ["confidence", "mergedText"]}})
File "C:\Users\manan.shah.virtualenvs\document_analysis-Q6JswU4T\lib\site-packages\proto\message.py", line 503, in init
"Unknown field for {}: {}".format(self.class.name, key)
ValueError: Unknown field for TextDetectionParams: lineFilter
PS C:\git\ds\document_analysis> pipenv run python .\spike\google_ocr.py
Loading .env environment variablesโ€ฆ
Traceback (most recent call last):
File "C:\Users\manan.shah.virtualenvs\document_analysis-Q6JswU4T\lib\site-packages\proto\message.py", line 497, in init
pb_type = self._meta.fields[key].pb_type
KeyError: 'disable_orientation_detection'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File ".\spike\google_ocr.py", line 84, in
"gs://manan-ocr-testing/tt",
File ".\spike\google_ocr.py", line 24, in async_detect_document
text_detection_params=vision.TextDetectionParams(disable_orientation_detection=True)
File "C:\Users\manan.shah.virtualenvs\document_analysis-Q6JswU4T\lib\site-packages\proto\message.py", line 503, in init
"Unknown field for {}: {}".format(self.class.name, key)
ValueError: Unknown field for TextDetectionParams: disable_orientation_detection`

class TextDetectionParams(proto.Message):

    Attributes:
        enable_text_detection_confidence_score (bool):
            By default, Cloud Vision API only includes confidence score
            for DOCUMENT_TEXT_DETECTION result. Set the flag to true to
            include confidence score for TEXT_DETECTION as well.

    enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9)

When I look at the documentation, there is not a disable_orientation_detection property within TextDetectionParams, although the google cloud vision API mentions it here.

https://cloud.google.com/vision/docs/reference/rest/v1p4beta1/ImageContext#TextDetectionParams

Any ideas what am I missing here?

Environment details

  • OS type and version: WIndows
  • Python version: 3.6.8
  • pip version: 20.2.3
  • google-cloud-vision version: 2.3.0

Thanks!

Vision API Error isn't thrown

Was updating some samples and found when calling the Google Cloud Vision API with the python client library which has some handwritten helper methods making it a partial GAPIC library, that if the users passes a URL that the API can't reach, the API returns an error message, but the client library doesn't throw the error rather returns it as part of the response.

Call request: response = client.text_detection(image=image)
If you examine the response object from the api you'll find this:

error {
  code: 3
  message: "The URL does not appear to be accessible by us. Please double check or download the content and pass it in."
}

Seems like we should throw this error.

Related PR that I discovered this in: GoogleCloudPlatform/python-docs-samples#2569

Vision - Using Batch Offline Annotation asynchronously

I am currently implementing a GCloud function applying the vision API to given images. Currently, the function is running for about 30 seconds (5 images) using the async_batch_annotate_images. My goal was to call the async method to leave the function early to save computing time.

This is the last part of my code, everything works so far:

    # loop over the images and prepare them

    source = {'image_uri': input_image_uri}
    image = {'source': source}
    type_ = enums.Feature.Type.TEXT_DETECTION
    features_element = {'type': type_}
    features = [features_element]
    requests_element = {'image': image, 'features': features}
    requests.append(requests_element)

gcs_destination = {'uri': output_uri}
output_config = {'gcs_destination': gcs_destination, 'batch_size': 1}

client.async_batch_annotate_images(requests, output_config)

return True

How is it possible to call the async method and terminate the function right after the call to save computing time?
(@tseaver maybe you could help?)

ModuleNotFoundError: No module named 'google.cloud'

In jupyter notebook:

image

Package got installed successfully but still it is giving me the following error:

image

I tried reinstalling the library but sill couldn't resolve this issue.

(When I am doing the same in Pycharm, there is no issue)

Google Cloud Server Forced Close when Querying for Object Localization

This issue is also uploaded to Stack Overflow at https://stackoverflow.com/questions/60943745/google-cloud-server-forced-close-when-querying-for-object-localization.

I sometimes get the error

google.api_core.exceptions.ServiceUnavailable: 503 Getting metadata from plugin failed with error: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

Upon running

# server/classifiers/gcloud/identifier.py


import io
import os
import json
from google.cloud import vision
from google.cloud.vision import types
from collections import Counter

client = vision.ImageAnnotatorClient()

with io.open("config/labels.json", "r") as f:
    LABELS = json.loads(f.read())


def identify_from_string(blob):
    image = types.Image(content=blob)
    response = client.object_localization(image=image)
    labels = response.localized_object_annotations
    objects = set(label.name for label in labels)

    c = Counter()
    for label, s in LABELS.items():
        for ob in objects:
            if ob in s:
                c[label] += s[ob]

    if not c: print("Sorry, the server is currently full.")
    return str(c)

With the error thrown on line with response = client.object_localization(image=image). On my app.py, I have

# server/app.py

import os
import json
from server.classifiers.gcloud import identifier
from flask import Flask, Response, render_template, send_file, request

@app.route('/classify', methods=['POST'])
def classify():
    app.logger.info("Got image to /classify")
    file = request.files['image']
    blob = file.read()
    results = identifier.identify_from_string(blob)
    return Response(response=json.dumps(dict(response)), status=200)

Where the server.classifiers.gcloud.identifier points to the file above. Occasionally, the issue suddenly goes away. Is there a way around this?

Update README Example Usage for v2

Environment details

  • OS type and version: macOS Mojave 10.14.6
  • Python version: Python 3.8.5
  • pip version: pip 20.2.3
  • google-cloud-vision version: 2.0.0

Steps to reproduce

  1. Run the example usage code: https://github.com/googleapis/python-vision#example-usage
  2. Get error 'google.cloud.vision' has no attribute 'enums'

Guessing this has to do with: https://googleapis.dev/python/vision/latest/UPGRADING.html

Code example

from google.cloud import vision

client = vision.ImageAnnotatorClient()
response = client.annotate_image({
  'image': {'source': {'image_uri': 'gs://my-test-bucket/image.jpg'}},
  'features': [{'type': vision.enums.Feature.Type.FACE_DETECTION}],
})

Stack trace

Traceback (most recent call last):
  File "example.py", line 6, in <module>
    'features': [{'type': vision.enums.Feature.Type.FACE_DETECTION}],
AttributeError: module 'google.cloud.vision' has no attribute 'enums'

Please Document if indeed Raspberry Pi ARMv6 is not supported

I have spent days trying to debug an "illegal instruction" on import google.cloud.vision on a RaspberryPi ARMv6, making sure everything was updated, correct versions, etc. to no avail, and cannot find a statement if or if not Raspberry Pi ARMv6 is supported anywhere on cloud.google.com developer documentation. There are some two year old frustrated user posts on the net saying "no longer supported" but nothing official anywhere. Would have been nice under the Linux/Debian tutorials and "Getting Started" stuff.

Since lots of Raspberry Pi with PiCamera users are trying google.cloud.vision, you all could really help them avoid buying the wrong Pi.

If not supported, could you all put "Note: Raspberry Pi ARMv6 is not supported by google.cloud" in the README.md for python-vision?

Segmentation Fault

Thanks for stopping by to let us know something could be better!

PLEASE READ: If you have a support contract with Google, please create an issue in the support console instead of filing on GitHub. This will ensure a timely response.

Please run down the following list and make sure you've tried the usual "quick fixes":

If you are still having issues, please be sure to include as much information as possible:

Environment details

  • OS type and version: Mac 11.0.1
  • Python version: python --version 3.7.9
  • pip version: pip --version 20.2.4
  • google-cloud-vision version: pip show google-cloud-vision
Name: google-cloud-vision
Version: 2.0.0
Summary: Cloud Vision API API client library
Home-page: https://github.com/googleapis/python-vision
Author: Google LLC
Author-email: [email protected]
License: Apache 2.0
Location: /Users/davidchen/repo/gchannel/venv/lib/python3.7/site-packages
Requires: google-api-core, proto-plus, libcst

Steps to reproduce

  1. open python
  2. import vision sdk

Code example

(venv) โžœ  src git:(fix-smart-animation) โœ— python                                                
Python 3.7.9 (default, Nov 12 2020, 11:53:23) 
[Clang 11.0.3 (clang-1103.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import google.cloud.vision
[1]    67548 segmentation fault  python

Stack trace

google-api-core[grpc]==1.23.0  # via google-api-python-client, google-cloud-core, google-cloud-datastore, google-cloud-pubsub, google-cloud-translate, google-cloud-vision
google-cloud-vision==2.0.0  
proto-plus==1.13.0        # via google-cloud-datastore, google-cloud-vision
libcst==0.3.15            # via google-cloud-datastore, google-cloud-vision

Making sure to follow these steps will guarantee the quickest resolution possible.

Thanks!

Synthesis failed for python-vision

Hello! Autosynth couldn't regenerate python-vision. ๐Ÿ’”

Here's the output from running synth.py:

loud/vision/v1/product_search_service.proto=google/cloud/vision/v1/product_search_service.proto -Igoogle/cloud/vision/v1/text_annotation.proto=google/cloud/vision/v1/text_annotation.proto -Igoogle/cloud/vision/v1/web_detection.proto=google/cloud/vision/v1/web_detection.proto -Igoogle/api/annotations.proto=google/api/annotations.proto -Igoogle/api/http.proto=google/api/http.proto -Igoogle/protobuf/descriptor.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/descriptor_proto/google/protobuf/descriptor.proto -Igoogle/api/client.proto=google/api/client.proto -Igoogle/api/field_behavior.proto=google/api/field_behavior.proto -Igoogle/api/resource.proto=google/api/resource.proto -Igoogle/longrunning/operations.proto=google/longrunning/operations.proto -Igoogle/rpc/status.proto=google/rpc/status.proto -Igoogle/protobuf/any.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/any_proto/google/protobuf/any.proto -Igoogle/protobuf/duration.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/duration_proto/google/protobuf/duration.proto -Igoogle/protobuf/empty.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/empty_proto/google/protobuf/empty.proto -Igoogle/type/color.proto=google/type/color.proto -Igoogle/protobuf/wrappers.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/wrappers_proto/google/protobuf/wrappers.proto -Igoogle/type/latlng.proto=google/type/latlng.proto -Igoogle/protobuf/field_mask.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/field_mask_proto/google/protobuf/field_mask.proto -Igoogle/protobuf/timestamp.proto=bazel-out/k8-fastbuild/bin/external/com_google_protobuf/_virtual_imports/timestamp_proto/google/protobuf/timestamp.proto google/cloud/vision/v1/geometry.proto google/cloud/vision/v1/image_annotator.proto google/cloud/vision/v1/product_search.proto google/cloud/vision/v1/product_search_service.proto google/cloud/vision/v1/text_annotation.proto google/cloud/vision/v1/web_detection.proto` failed (Exit 1) protoc failed: error executing command bazel-out/host/bin/external/com_google_protobuf/protoc --experimental_allow_proto3_optional '--plugin=protoc-gen-python_gapic=bazel-out/host/bin/external/gapic_generator_python/gapic_plugin' ... (remaining 29 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox
google/cloud/vision/v1/geometry.proto:20:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/product_search.proto:23:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/text_annotation.proto:21:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/web_detection.proto:20:1: warning: Import google/api/annotations.proto is unused.
google/cloud/vision/v1/image_annotator.proto:28:1: warning: Import google/protobuf/field_mask.proto is unused.
Traceback (most recent call last):
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/cli/generate_with_pandoc.py", line 3, in <module>
    from gapic.cli import generate
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/cli/generate.py", line 23, in <module>
    from gapic import generator
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/generator/__init__.py", line 21, in <module>
    from .generator import Generator
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/generator/generator.py", line 24, in <module>
    from gapic.samplegen import manifest, samplegen
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/samplegen/__init__.py", line 15, in <module>
    from gapic.samplegen import samplegen
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/samplegen/samplegen.py", line 27, in <module>
    from gapic.schema import wrappers
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/schema/__init__.py", line 23, in <module>
    from gapic.schema.api import API
  File "/home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/sandbox/linux-sandbox/50/execroot/com_google_googleapis/bazel-out/host/bin/external/gapic_generator_python/gapic_plugin.runfiles/gapic_generator_python/gapic/schema/api.py", line 29, in <module>
    from google.api_core import exceptions  # type: ignore
ModuleNotFoundError: No module named 'google.api_core'
--python_gapic_out: protoc-gen-python_gapic: Plugin failed with status code 1.
Target //google/cloud/vision/v1:vision-v1-py failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 1.052s, Critical Path: 0.83s
INFO: 0 processes.
FAILED: Build did NOT complete successfully
FAILED: Build did NOT complete successfully

Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 102, in <module>
    main()
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 94, in main
    spec.loader.exec_module(synth_module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/kbuilder/.cache/synthtool/python-vision/synth.py", line 34, in <module>
    include_protos=True
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 52, in py_library
    return self._generate_code(service, version, "python", **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 193, in _generate_code
    shell.run(bazel_run_args)
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 39, in run
    raise exc
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 33, in run
    encoding="utf-8",
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 438, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['bazel', '--max_idle_secs=240', 'build', '//google/cloud/vision/v1:vision-v1-py']' returned non-zero exit status 1.
2021-01-21 05:49:16,884 autosynth [ERROR] > Synthesis failed
2021-01-21 05:49:16,884 autosynth [DEBUG] > Running: git reset --hard HEAD
HEAD is now at d81f83a chore(deps): update dependency pillow to v8.1.0 (#90)
2021-01-21 05:49:16,890 autosynth [DEBUG] > Running: git checkout autosynth
Switched to branch 'autosynth'
2021-01-21 05:49:16,895 autosynth [DEBUG] > Running: git clean -fdx
Removing __pycache__/
Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 354, in <module>
    main()
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 189, in main
    return _inner_main(temp_dir)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 334, in _inner_main
    commit_count = synthesize_loop(x, multiple_prs, change_pusher, synthesizer)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 65, in synthesize_loop
    has_changes = toolbox.synthesize_version_in_new_branch(synthesizer, youngest)
  File "/tmpfs/src/github/synthtool/autosynth/synth_toolbox.py", line 259, in synthesize_version_in_new_branch
    synthesizer.synthesize(synth_log_path, self.environ)
  File "/tmpfs/src/github/synthtool/autosynth/synthesizer.py", line 120, in synthesize
    synth_proc.check_returncode()  # Raise an exception.
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 389, in check_returncode
    self.stderr)
subprocess.CalledProcessError: Command '['/tmpfs/src/github/synthtool/env/bin/python3', '-m', 'synthtool', '--metadata', 'synth.metadata', 'synth.py', '--']' returned non-zero exit status 1.

Google internal developers can see the full log here.

TextAnnotation doesn't have orientationDegrees

REST v1 AnnotateImageResponse already returns orientationDegrees https://cloud.google.com/vision/docs/reference/rest/v1/AnnotateImageResponse#Page but looks like this library proto files hasn't been updated for a while:
https://github.com/googleapis/googleapis/blob/master/google/cloud/vision/v1/text_annotation.proto#L96
https://github.com/googleapis/googleapis/blob/master/google/cloud/vision/v1p4beta1/text_annotation.proto#L98

Environment details

  • google-cloud-vision version: 2.3.0

Steps to reproduce

  1. Send any DOCUMENT_TEXT_DETECTION request to REST \ with this library
  2. check Pages

A similar issue #138

Synthesis failed for python-vision

Hello! Autosynth couldn't regenerate python-vision. ๐Ÿ’”

Here's the output from running synth.py:

uilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:123:1
Loading: 0 packages loaded
INFO: SHA256 (https://github.com/grpc/grpc-java/archive/v1.27.2.zip) = 92ffb4391f847e02e115933a761e243dd1423f3fcafdc9b7ae0327eca102d76b
DEBUG: Rule 'io_grpc_grpc_java' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "92ffb4391f847e02e115933a761e243dd1423f3fcafdc9b7ae0327eca102d76b"
DEBUG: Call stack for the definition of repository 'io_grpc_grpc_java' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/com_google_api_gax_java/repositories.bzl:114:5
 - /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/com_google_api_gax_java/repositories.bzl:60:5
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:138:1
Loading: 0 packages loaded
INFO: SHA256 (https://github.com/googleapis/gapic-generator/archive/a59457d24bd6f3c962c8e699c708121c928eedc8.zip) = 843bcf262d44f6a2c1c131844ff8ef40daf95dd3b7c95dd761656f9e010d06d7
DEBUG: Rule 'com_google_api_codegen' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "843bcf262d44f6a2c1c131844ff8ef40daf95dd3b7c95dd761656f9e010d06d7"
DEBUG: Call stack for the definition of repository 'com_google_api_codegen' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:62:1
Loading: 0 packages loaded
INFO: SHA256 (https://github.com/googleapis/protoc-java-resource-names-plugin/archive/64dafb71ea9a385a8da89989f0b9dab925bf4610.zip) = f475903e83904dbbe3651abae8cbf57ed804960a0dadd9cbde41b746db645052
DEBUG: Rule 'com_google_protoc_java_resource_names_plugin' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "f475903e83904dbbe3651abae8cbf57ed804960a0dadd9cbde41b746db645052"
DEBUG: Call stack for the definition of repository 'com_google_protoc_java_resource_names_plugin' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:155:1
INFO: SHA256 (https://github.com/googleapis/protoc-docs-plugin/archive/b2502d56b5ec2d47e063976da773206af295362d.zip) = 765ec120bb165ae98c3bae78705d2a127e64016e59738552e909fc8b11d06338
DEBUG: Rule 'protoc_docs_plugin' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "765ec120bb165ae98c3bae78705d2a127e64016e59738552e909fc8b11d06338"
DEBUG: Call stack for the definition of repository 'protoc_docs_plugin' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:179:1
Loading: 0 packages loaded
INFO: SHA256 (https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.20.0/bazel-gazelle-v0.20.0.tar.gz) = d8c45ee70ec39a57e7a05e5027c32b1576cc7f16d9dd37135b0eddde45cf1b10
DEBUG: Rule 'bazel_gazelle' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "d8c45ee70ec39a57e7a05e5027c32b1576cc7f16d9dd37135b0eddde45cf1b10"
DEBUG: Call stack for the definition of repository 'bazel_gazelle' which is a http_archive (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/bazel_tools/tools/build_defs/repo/http.bzl:296:16):
 - <builtin>
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:200:1
Analyzing: target //google/cloud/vision/v1:vision-v1-py (1 packages loaded, 0 targets configured)
INFO: Call stack for the definition of repository 'go_sdk' which is a _go_download_sdk (rule definition at /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/io_bazel_rules_go/go/private/sdk.bzl:79:20):
 - <builtin>
 - /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/io_bazel_rules_go/go/private/sdk.bzl:92:5
 - /home/kbuilder/.cache/bazel/_bazel_kbuilder/a732f932c2cbeb7e37e1543f189a2a73/external/io_bazel_rules_go/go/private/sdk.bzl:260:13
 - /home/kbuilder/.cache/synthtool/googleapis/WORKSPACE:81:1
ERROR: While resolving toolchains for target @pypi_black//:black: invalid registered toolchain '@gapic_generator_python//:pyenv3_toolchain': no such package '@gapic_generator_python//': The repository '@gapic_generator_python' could not be resolved
ERROR: Analysis of target '//google/cloud/vision/v1:vision-v1-py' failed; build aborted: invalid registered toolchain '@gapic_generator_python//:pyenv3_toolchain': no such package '@gapic_generator_python//': The repository '@gapic_generator_python' could not be resolved
INFO: Elapsed time: 6.549s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (21 packages loaded, 22 targets configured)
FAILED: Build did NOT complete successfully (21 packages loaded, 22 targets configured)

2020-06-20 08:42:46,315 synthtool [DEBUG] > Wrote metadata to synth.metadata.
Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 102, in <module>
    main()
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/tmpfs/src/github/synthtool/env/lib/python3.6/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/__main__.py", line 94, in main
    spec.loader.exec_module(synth_module)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/kbuilder/.cache/synthtool/python-vision/synth.py", line 33, in <module>
    include_protos=True
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 46, in py_library
    return self._generate_code(service, version, "python", **kwargs)
  File "/tmpfs/src/github/synthtool/synthtool/gcp/gapic_bazel.py", line 180, in _generate_code
    shell.run(bazel_run_args)
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 39, in run
    raise exc
  File "/tmpfs/src/github/synthtool/synthtool/shell.py", line 33, in run
    encoding="utf-8",
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 438, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['bazel', '--max_idle_secs=60', 'build', '//google/cloud/vision/v1:vision-v1-py']' returned non-zero exit status 1.
2020-06-20 08:42:46,358 autosynth [ERROR] > Synthesis failed
2020-06-20 08:42:46,359 autosynth [DEBUG] > Running: git reset --hard HEAD
HEAD is now at b33fa88 docs: added note about not supported device (#24)
2020-06-20 08:42:46,364 autosynth [DEBUG] > Running: git checkout autosynth-self
Switched to branch 'autosynth-self'
2020-06-20 08:42:46,370 autosynth [ERROR] > Command '['/tmpfs/src/github/synthtool/env/bin/python3', '-m', 'synthtool', '--metadata', 'synth.metadata', 'synth.py', '--']' returned non-zero exit status 1.
2020-06-20 08:42:46,576 autosynth [INFO] > PR already exists: https://github.com/googleapis/python-vision/pull/27
2020-06-20 08:42:46,576 autosynth [DEBUG] > Running: git clean -fdx
Removing __pycache__/
Removing google/__pycache__/
Traceback (most recent call last):
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 649, in <module>
    main()
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 506, in main
    return _inner_main(temp_dir)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 629, in _inner_main
    commit_count = synthesize_loop(x, multiple_prs, change_pusher, synthesizer)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 367, in synthesize_loop
    synthesize_inner_loop(fork, synthesizer)
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 411, in synthesize_inner_loop
    synthesizer, len(toolbox.versions) - 1
  File "/tmpfs/src/github/synthtool/autosynth/synth.py", line 266, in synthesize_version_in_new_branch
    synthesizer.synthesize(synth_log_path, self.environ)
  File "/tmpfs/src/github/synthtool/autosynth/synthesizer.py", line 120, in synthesize
    synth_proc.check_returncode()  # Raise an exception.
  File "/home/kbuilder/.pyenv/versions/3.6.9/lib/python3.6/subprocess.py", line 389, in check_returncode
    self.stderr)
subprocess.CalledProcessError: Command '['/tmpfs/src/github/synthtool/env/bin/python3', '-m', 'synthtool', '--metadata', 'synth.metadata', 'synth.py', '--']' returned non-zero exit status 1.

Google internal developers can see the full log here.

How to serialize to json or dict that response from vision api?

Hi,

Google Cloud SDK works well to get annotation responses via vision API, and I just like to know how can I serialize the response. Is there any helper or serializer for Google response objects? Otherwise, should I parse and build dictionaries from the response object by manual?

  1. OS type and version
    OS X El Capitan
  2. Python version and virtual environment information python --version
    2.7.13
  3. google-cloud-python version pip show google-cloud, pip show google-<service> or pip freeze
    157.0.0
  4. Stacktrace if available
  5. Steps to reproduce
  6. Code example

Protobuf messages can no longer be deserialized after migration to 2.0.0

Environment details

  • OS type and version: macOS 10.14.6 - also reproduced with Linux CentOS 7
  • Python version: 3.6.10
  • pip version: 18.1
  • google-cloud-vision version: 2.0.0
  • protobuf version: 3.13.0

Steps to reproduce

  1. Run client.annotate_image(request)=> SUCCESS (request is valid and you can print the output)
  2. Try to deserialized message => FAILURE AttributeError: 'DESCRIPTOR'

Code example

from google.protobuf.json_format import MessageToDict
message = client.annotate_image(request)
print(message)  # this works
MessageToDict(message)  # this fails

Stack trace

[12:09:25] [INFO] [dku.utils]  - responses {
[12:09:25] [INFO] [dku.utils]  -   localized_object_annotations {
[12:09:25] [INFO] [dku.utils]  -     mid: "/m/02dl1y"
[12:09:25] [INFO] [dku.utils]  -     name: "Hat"
[12:09:25] [INFO] [dku.utils]  -     score: 0.509366512298584
[12:09:25] [INFO] [dku.utils]  -     bounding_poly {
[12:09:25] [INFO] [dku.utils]  -       normalized_vertices {
[12:09:25] [INFO] [dku.utils]  -         x: 0.005275096278637648
[12:09:25] [INFO] [dku.utils]  -         y: 0.008623555302619934
[12:09:25] [INFO] [dku.utils]  -       }
[12:09:25] [INFO] [dku.utils]  -       normalized_vertices {
[12:09:25] [INFO] [dku.utils]  -         x: 0.9973958134651184
[12:09:25] [INFO] [dku.utils]  -         y: 0.008623555302619934
[12:09:25] [INFO] [dku.utils]  -       }
[12:09:25] [INFO] [dku.utils]  -       normalized_vertices {
[12:09:25] [INFO] [dku.utils]  -         x: 0.9973958134651184
[12:09:25] [INFO] [dku.utils]  -         y: 0.9851147532463074
[12:09:25] [INFO] [dku.utils]  -       }
[12:09:25] [INFO] [dku.utils]  -       normalized_vertices {
[12:09:25] [INFO] [dku.utils]  -         x: 0.005275096278637648
[12:09:25] [INFO] [dku.utils]  -         y: 0.9851147532463074
[12:09:25] [INFO] [dku.utils]  -       }
[12:09:25] [INFO] [dku.utils]  -     }
[12:09:25] [INFO] [dku.utils]  -   }
[12:09:25] [INFO] [dku.utils]  - }
[12:09:25] [INFO] [dku.utils]  - responses {
[12:09:25] [INFO] [dku.utils]  - *************** Recipe code failed **************
[12:09:25] [INFO] [dku.utils]  - }
[12:09:25] [INFO] [dku.utils]  - Begin Python stack
[12:09:25] [INFO] [dku.utils]  - responses {
[12:09:25] [INFO] [dku.utils]  - Traceback (most recent call last):
[12:09:25] [INFO] [dku.utils]  - }
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/code-envs/python/plugin_google-cloud-vision_managed_2/lib/python3.6/site-packages/proto/message.py", line 520, in __getattr__
[12:09:25] [INFO] [dku.utils]  -     pb_type = self._meta.fields[key].pb_type
[12:09:25] [INFO] [dku.utils]  - KeyError: 'DESCRIPTOR'
[12:09:25] [INFO] [dku.utils]  - During handling of the above exception, another exception occurred:
[12:09:25] [INFO] [dku.utils]  - Traceback (most recent call last):
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/jobs/TESTGOOGLEVISIONPLUGIN/Build_cloud_content__me__2020-10-13T10-09-12.241/compute_cloud_content_me/custom-python-recipe/pyouthtnvsUANhkXA/python-exec-wrapper.py", line 206, in <module>
[12:09:25] [INFO] [dku.utils]  -     exec(f.read())
[12:09:25] [INFO] [dku.utils]  -   File "<string>", line 58, in <module>
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/plugins/dev/google-cloud-vision/python-lib/api_parallelizer.py", line 201, in api_parallelizer
[12:09:25] [INFO] [dku.utils]  -     api_results.append(f.result())
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/.pyenv/versions/3.6.10/lib/python3.6/concurrent/futures/_base.py", line 425, in result
[12:09:25] [INFO] [dku.utils]  -     return self.__get_result()
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/.pyenv/versions/3.6.10/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
[12:09:25] [INFO] [dku.utils]  -     raise self._exception
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/.pyenv/versions/3.6.10/lib/python3.6/concurrent/futures/thread.py", line 56, in run
[12:09:25] [INFO] [dku.utils]  -     result = self.fn(*self.args, **self.kwargs)
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/plugins/dev/google-cloud-vision/python-lib/api_parallelizer.py", line 109, in api_call_batch
[12:09:25] [INFO] [dku.utils]  -     batch = batch_api_response_parser(batch=batch, response=response, api_column_names=api_column_names)
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/plugins/dev/google-cloud-vision/python-lib/google_vision_api_client.py", line 78, in batch_api_response_parser
[12:09:25] [INFO] [dku.utils]  -     response_dict = MessageToDict(response)
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/code-envs/python/plugin_google-cloud-vision_managed_2/lib/python3.6/site-packages/google/protobuf/json_format.py", line 175, in MessageToDict
[12:09:25] [INFO] [dku.utils]  -     return printer._MessageToJsonObject(message)
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/code-envs/python/plugin_google-cloud-vision_managed_2/lib/python3.6/site-packages/google/protobuf/json_format.py", line 209, in _MessageToJsonObject
[12:09:25] [INFO] [dku.utils]  -     message_descriptor = message.DESCRIPTOR
[12:09:25] [INFO] [dku.utils]  -   File "/Users/alexandrecombessie/Library/DataScienceStudio/dss_home/code-envs/python/plugin_google-cloud-vision_managed_2/lib/python3.6/site-packages/proto/message.py", line 525, in __getattr__
[12:09:25] [INFO] [dku.utils]  -     raise AttributeError(str(ex))
[12:09:25] [INFO] [dku.utils]  - AttributeError: 'DESCRIPTOR'

I read other issues, and it seems this bug is linked to 2 other issues: #60 #58

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.