0

I am using the Google Vision Rest API to extract text from an image

VISION_API_ENDPOINT = 'https://vision.googleapis.com/v1/images:annotate'
def get_response(self, img_bytes):
    # Payload for text detection request
    data = {
        "requests": [{
            "image": {
                "content":  base64.b64encode(img_bytes).decode("utf-8")
            },
            "features": [{
                "type": "TEXT_DETECTION"
            }],
        "imageContext": {
                "languageHints": ["en"]
            }
        }]
    }
    
    response = requests.post(VISION_API_ENDPOINT, headers=self.request_headers, json=data)
    return response.json()

I was making many requests to the API to extract text from small images (128x32 size). After around 7000 requests, the following error occurred -

Traceback (most recent call last):
  File "/path/to/file", line 97, in get_labels
    texts = response["responses"][0]
KeyError: 'responses

The error kept occurring for all the subsequent images. Unfortunately, I did not log the response for this exception. I do not have access to the images for which this exception occurred since they were generated on-the-fly (I am working on reproducing the error). The GCP console shows that there was no error for any of the requests, so I am not sure why the "responses" key is not present. Any help would be appreciated.

Ganesh Tata
  • 1,118
  • 8
  • 26
  • Often there is rate limit set on an API like this. You should check the docs and limit your request to `x` amount of request per second. – Bas van der Linden Mar 14 '23 at 21:53
  • @BasvanderLinden Thank you. I am making only around 4 requests per second, so that shouldn't be a problem. – Ganesh Tata Mar 14 '23 at 21:56
  • 1
    Ah okay, the best option is to try-catch the error and print the response. It's possible that there are variations in the response depending on if there was/wasn't a result or if the input image is different then others etc. Good Luck! – Bas van der Linden Mar 14 '23 at 22:01

0 Answers0