'How to use Google Cloud Vision API in Firebase Cloud Functions?

I'm using the Cloud Vision API in Firebase Cloud Functions. I can successfully send a request to Cloud Vision API and see the results while working in my local environment. When I deploy the code, the annotateImage function does not work properly. It returns a safeSearchAnnotation that is null and labelAnnotations that is empty. To test the API locally, I've generated a service account and a key with that service account. Then I exported the path to the key with:

export GOOGLE_APPLICATION_CREDENTIALS=${pathToTheKey}

This lets me use the API locally but I haven't done anything else to be able to use the API on production since it's stated that enabling the API in Google Cloud Console suffices. The API is already enabled. What could be the problem here?

Environment details

  • OS: The API call is made in Cloud Functions. So the OS is whatever Google chooses to run the Cloud Functions on.
  • Node.js version: The node version specified in package.json is 14.
  • npm version: I don't have access to the npm version since the API call is made on a Cloud Function.
  • @google-cloud/vision version: ^2.4.2


Solution 1:[1]

Based from the error you got, you are using a public image URL (Please correct me if I'm mistaken). This is an expected behavior and you will encounter this error from time to time since there is no guarantee that the image is readily available. The host of the image might deny some request for DOS prevention. See imageUri reference for more details.

A publicly-accessible image HTTP/HTTPS URL. When fetching images from HTTP/HTTPS URLs, Google cannot guarantee that the request will be completed. Your request may fail if the specified host denies the request (e.g. due to request throttling or DOS prevention), or if Google throttles requests to the site for abuse prevention. You should not depend on externally-hosted images for production applications.

The error also returned code 4 which refers to DEADLINE_EXCEEDED. What I could suggest are the following:

  • Try extending the timeout and adding retry on your code just to check if this could bypass the error. AFAIK in NodeJS you can pass these parameters using CallOptions.
  • If the 1st workaround did not work, I recommend to host the images/content to Google Cloud Storage (since your are using a Cloud Function) as this is the recommend way for you to process your images/content consistently.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ricco D