【发布时间】:2021-08-15 06:28:44
【问题描述】:
我一直在尝试使用 Google.Apis.Translate.v3beta1 的 .NET API 来翻译 PPTX 或 DOCX 文件,同时保留文档格式。理论上,根据https://cloud.google.com/translate/docs/advanced/translate-documents#translate_documents_online 中的描述,这是可能的,但是文档太差了,无法猜测它应该如何工作。
我希望有人知道这个 API 应该如何工作。
这是我尝试过的。
- 创建了一个启用 Cloud Translation API 的 Google Cloud 项目。
- 创建了服务帐号并下载了私钥。
- 创建了一个bucket并上传了一个文件AZ01.ppt进行翻译。
- 确保服务帐户有权访问翻译 API。我做了这个使用 Google.Cloud.Translation.V2 和我可以在没有的情况下翻译文本 问题。
正如文档所暗示的,这是我在 C# 中的代码:
public async Task doitAsync()
{
string keyFile = @"mykeyfile.p12";
// Get the certificate
var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);
// Create the credential so we can generate an access token
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer("mysaerviceaccount@myaccount.iam.gserviceaccount.com")
{
Scopes = new[] { Google.Apis.Translate.v3beta1.TranslateService.Scope.CloudTranslation },
ProjectId = "myproject",
KeyId = "some long key like 3aedc7cfe17d2ad83813f162f4af50597bade165d619d65eab6b5"
}.FromCertificate(certificate));
// Get a request token
bool success = await credential.RequestAccessTokenAsync(new CancellationToken());
string token = credential.Token.AccessToken;
string json = File.ReadAllText("params.json");
Google.Apis.Translate.v3beta1.TranslateService serv = new Google.Apis.Translate.v3beta1.TranslateService();
var client = serv.HttpClient;
client.BaseAddress = new Uri("https://translation.googleapis.com/v3beta1/projects");
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(
"https://translation.googleapis.com/v3beta1/projects/myproject/locations/global:translateDocument?access_token=" + token,
httpContent);
if (response.IsSuccessStatusCode)
{
string res = await response.Content.ReadAsStringAsync();
Console.WriteLine("Success: " + res);
}
else
{
string res = await response.Content.ReadAsStringAsync();
Console.WriteLine("Failure: " + res);
}
}
执行这段代码的结果总是:
Failure: {
"error": {
"code": 403,
"message": "Provided scope(s) are not authorized",
"errors": [
{
"message": "Provided scope(s) are not authorized",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
但是,我的服务帐户与 Translation API 相关联。
所以我希望那里有人对 Google.Apis.Translate.v3beta1 的 .NET API 有一些经验,并且可以阐明应该如何调用它,或者可以指出我缺少什么.
【问题讨论】:
标签: c# google-cloud-platform google-api google-translate google-translation-api