如何使用windows应用程序创建谷歌翻译而不出现错误应用程序默认凭据不可用



我正在尝试创建一个谷歌api来从图像中提取文本,然后翻译成英语,我的示例代码如下

try
{
var JsonFilePath = @"C:UsersshanjeevasourcereposTranslatorWindowsAppTranslator-fa8e022a7ba1.json";
//Authenticate to the service by using Service Account
var credential = GoogleCredential.FromFile(JsonFilePath).CreateScoped(ImageAnnotatorClient.DefaultScopes);
var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
var client = ImageAnnotatorClient.Create(); // getting an error here
var image = Image.FromFile(@"D:Work TempTranslate.JPG");
// Performs label detection on the image file
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
}
catch (AnnotateImageException ex)
{
AnnotateImageResponse response = ex.Response;
Console.WriteLine(response.Error);
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
throw;
}
}

此外,我还设置了谷歌云应用程序,生成了必要的json文件,如Translator-XXXX.json

一些人建议用键"设置环境变量;GOOGLE_APPLICATION_CREDENTIALS";我也试过了,但出现错误

'应用程序默认凭据不可用。如果在谷歌计算引擎中运行,它们是可用的。否则,必须定义指向定义凭据的文件的环境变量GOOGLE_APPLICATION_CREDENTIALS。看见https://developers.google.com/accounts/docs/application-default-credentials了解更多信息

有人能帮帮我吗?

我能够在专家的帮助下解决问题,示例代码如下所示,在所有其他代码之前添加了如下代码,它可以很好地进行

try
{
var GAC = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
if (GAC == null)
{
var path = @"D:Work Temptranslator-298603-2bb5a20655a2.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
}
}
catch (Exception)
{
}

相关内容

  • 没有找到相关文章