如何在 Firebase Cloud Functions 中使用 Google Cloud Vision API?

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

我在 Firebase Cloud Functions 中使用 Cloud Vision API。我可以成功向 Cloud Vision API 发送请求并在我的本地环境中查看结果。当我部署代码时,annotateImage 函数无法正常工作。它 returns 一个 safeSearchAnnotation 是空的,labelAnnotations 是空的。为了在本地测试 API,我生成了一个服务帐户和该服务帐户的密钥。然后我将路径导出到密钥:

export GOOGLE_APPLICATION_CREDENTIALS=${pathToTheKey}

这让我可以在本地使用 API,但我没有做任何其他事情来在生产中使用 API,因为它声明在 Google云控制台就够了。 API 已经启用。这可能是什么问题?

环境详情

根据您得到的错误,您使用的是public图像URL(如果我弄错了请纠正我)。这是预期的行为,您会不时遇到此错误,因为无法保证图像随时可用。映像的主机可能会拒绝某些 DOS 防护请求。有关详细信息,请参阅 imageUri 参考资料。

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.

错误还返回 code 4,它指的是 DEADLINE_EXCEEDED。我可以提出以下建议:

  • 尝试扩展 timeout 并在您的代码中添加 retry 以检查这是否可以绕过错误。 AFAIK 在 NodeJS 中,您可以使用 CallOptions.
  • 传递这些参数
  • 如果第一个解决方法不起作用,我建议将 images/content 托管到 Google Cloud Storage(因为您使用的是 Cloud Function),因为这是您推荐的处理方式你的 images/content 始终如一。