英文:
How to add GOOGLE_APPLICATION_CREDENTIAL to Vision when hosted outside of GCP
问题
我正在尝试在Vercel上设置一个无服务器函数,该函数使用Google Vision OCR来注释图像。我能够在本地成功地执行此操作,但在如何添加GOOGLE_APPLICATION_CREDENTIALS
到Vision OCR上遇到了困难。我已将完整的service-key.json文件存储在名为GOOGLE_APPLICATION_CREDENTIALS
的环境变量中,但这并没有起作用。
以下是代码的简要概述:
import vision from '@google-cloud/vision';
const vision = vision.ImageAnnotatorClient();
const analyze = async (req, res) => {
const [result] = await client.textDetection(req.body.image);
res.send(result)
}
我尝试过使用google-auth-library
并打印出身份验证令牌,以便我可以调用Google的REST API,但这也没有起作用。
英文:
I am trying to set up a serverless function on vercel, which uses Google Vision OCR to annotate the images. I am able to successfully do it locally but having a hard time figuring out how to add the GOOGLE_APPLICATION_CREDENTIALS
on Vision OCR. I have stored the full service-key.json file in an environment called GOOGLE_APPLICATION_CREDENTIALS
but that did not do anything.
Here is a brief overview of the code:
import vision from '@google-cloud/vision';
const vision = vision.ImageAnnotatorClient();
const analyze = async (req, res) => {
const [result] = await client.textDetection(req.body.image);
res.send(result)
}
I have tried using google-auth-library
and printing out an auth token so that I could call the Google REST API but that did not work either
答案1
得分: 0
阅读了这篇博客之后,我发现我们可以使用google-auth-library手动配置凭据,而无需在机器环境中设置它。经过一番挖掘,我还发现ImageAnnotatorClient
接受一个auth
键用于凭据。在将所有这些内容拼接在一起后,以下是对我有效的最终代码:
import vision from '@google-cloud/vision';
import { GoogleAuth } from 'google-auth-library';
const credentials = JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS);
const auth = new GoogleAuth({ credentials });
const client = new vision.ImageAnnotatorClient({ auth });
const analyze = async (req, res) => {
const [result] = await client.textDetection(req.body.image);
res.send(result);
}
正如我在问题中提到的,我将来自Google的整个service-key.json文件保存为纯字符串对象,并将整个环境变量解析并添加到认证生成器中。
英文:
After reading this blog, I was able to find that we can use the google-auth-library to configure the credentials manually without setting it up in the environment of the machine. And after a bit of digging around I also found that ImageAnnotatorClient
takes an auth
key for credentials. After patching it all together this was the final code that worked for me:
import vision from '@google-cloud/vision';
import {GoogleAuth} from 'google-auth-library';
const credentials = JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS);
const auth = new GoogleAuth({credentials});
const client = new vision.ImageAnnotatorClient({auth});
const analyze = async (req, res) => {
const [result] = await client.textDetection(req.body.image);
res.send(result);
}
As mentioned in my question I saved the entire service-key.json file from google as plain string object in vercel env keys. Then I just parsed the whole env variable and added it to the auth generator.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论