-
Notifications
You must be signed in to change notification settings - Fork 1
/
Translator.cs
67 lines (56 loc) · 2.21 KB
/
Translator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Translate.v3beta1;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace GoogleApisTranslateWrapper
{
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
public class Translator
{
TranslateService _translateService;
string _projectId;
public Translator()
{
var keyJsonFilepath = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
@"key.json");
try
{
var credential = GoogleCredential.FromFile(keyJsonFilepath);
if (!(credential.UnderlyingCredential is ServiceAccountCredential))
throw new Exception("key.json should define a ServiceAccountCredential");
_projectId = ((ServiceAccountCredential)credential.UnderlyingCredential).ProjectId;
if (credential.IsCreateScopedRequired)
credential = credential.CreateScoped(TranslateService.Scope.CloudTranslation);
_translateService = new TranslateService(new BaseClientService.Initializer
{
ApplicationName = nameof(GoogleApisTranslateWrapper),
HttpClientInitializer = credential
});
}
catch (Exception ex)
{
}
}
public string Translate(string text, string sourceLang, string targetLang)
{
var translateTextRequest = _translateService.Projects.TranslateText(
new Google.Apis.Translate.v3beta1.Data.TranslateTextRequest()
{
Contents = new List<string>() { text },
SourceLanguageCode = sourceLang,
TargetLanguageCode = targetLang,
},
$"projects/{_projectId}");
var translateTextResponse = translateTextRequest.Execute();
return translateTextResponse.Translations[0].TranslatedText;
}
}
}