generated from karashiiro/DalamudPluginProjectTemplate
-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
DeepLTranslator.cs
307 lines (272 loc) · 8.86 KB
/
DeepLTranslator.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// <copyright file="DeepLTranslator.cs" company="lokinmodar">
// Copyright (c) lokinmodar. All rights reserved.
// Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License license.
// </copyright>
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Dalamud.Plugin.Services;
using DeepL;
using Newtonsoft.Json;
namespace Echoglossian
{
public partial class DeepLTranslator : ITranslator
{
private readonly IPluginLog pluginLog;
private readonly bool isUsingAPIKey;
private readonly Translator client;
private readonly HttpClient httpClient;
private readonly Random rndId;
private const string FreeEndpoint = "https://www2.deepl.com/jsonrpc";
public DeepLTranslator(IPluginLog pluginLog, bool isUsingAPIKey, string translatorKey)
{
this.pluginLog = pluginLog;
this.isUsingAPIKey = isUsingAPIKey;
if (isUsingAPIKey && !string.IsNullOrEmpty(translatorKey))
{
this.client = new(translatorKey);
return;
}
this.rndId = new Random(Guid.NewGuid().GetHashCode());
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
};
this.httpClient = new HttpClient(handler);
// Setting HTTP headers to mimic a request from the DeepL iOS App
this.httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
this.httpClient.DefaultRequestHeaders.Add("x-app-os-name", "iOS");
this.httpClient.DefaultRequestHeaders.Add("x-app-os-version", "16.3.0");
this.httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.9");
this.httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
this.httpClient.DefaultRequestHeaders.Add("x-app-device", "iPhone13,2");
this.httpClient.DefaultRequestHeaders.Add("User-Agent", "DeepL-iOS/2.9.1 iOS 16.3.0 (iPhone13,2)");
this.httpClient.DefaultRequestHeaders.Add("x-app-build", "510265");
this.httpClient.DefaultRequestHeaders.Add("x-app-version", "2.9.1");
this.httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
}
async Task<string> ITranslator.TranslateAsync(string text, string sourceLanguage, string targetLanguage)
{
if (this.isUsingAPIKey)
{
return await this.TranslateAsync(text, sourceLanguage, targetLanguage);
}
else
{
return await this.FreeTranslateAsync(text, sourceLanguage, targetLanguage);
}
}
string ITranslator.Translate(string text, string sourceLanguage, string targetLanguage)
{
if (this.isUsingAPIKey)
{
return this.Translate(text, sourceLanguage, targetLanguage);
}
else
{
return this.FreeTranslateAsync(text, sourceLanguage, targetLanguage).Result;
}
}
private string Translate(string text, string sourceLanguage, string targetLanguage)
{
this.pluginLog.Debug("inside DeepLTranslator Translate method");
try
{
var translation = this.client.TranslateTextAsync(
text,
this.FormatSourceLanguage(sourceLanguage),
this.FormatTargetLanguage(targetLanguage)).Result;
this.pluginLog.Debug($"FinalTranslatedText: {translation.Text}");
return translation.Text;
}
catch (Exception exception)
{
this.pluginLog.Warning($"DeepLTranslator Translate: {exception.Message}");
return text;
}
}
private async Task<string> TranslateAsync(string text, string sourceLanguage, string targetLanguage)
{
this.pluginLog.Debug("inside DeepLTranslator TranslateAsync method");
try
{
var translation = await this.client.TranslateTextAsync(
text,
this.FormatSourceLanguage(sourceLanguage),
this.FormatTargetLanguage(targetLanguage));
this.pluginLog.Debug($"FinalTranslatedText: {translation.Text}");
return translation.Text;
}
catch (Exception exception)
{
this.pluginLog.Warning($"DeepLTranslator TranslateAsync: {exception.Message}");
return text;
}
}
private int GetICount(string translateText)
{
return translateText.Count(c => c == 'i');
}
private long GetTimestamp(int iCount)
{
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (iCount == 0)
{
return timestamp;
}
iCount++;
return timestamp - (timestamp % iCount) + iCount;
}
/// <summary>
/// Translates a string using the Free DeepL API.
/// </summary>
/// <param name="text"></param>
/// <param name="sourceLanguage"></param>
/// <param name="targetLanguage"></param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
private async Task<string> FreeTranslateAsync(string text, string sourceLanguage, string targetLanguage)
{
this.pluginLog.Debug("inside DeepLTranslator FreeTranslateAsync method");
try
{
long timestamp = this.GetTimestamp(this.GetICount(text));
var id = this.rndId.Next(11111111, 99999999);
var requestBody = new
{
jsonrpc = "2.0",
method = "LMT_handle_texts",
@params = new
{
splitting = "newlines",
lang = new
{
target_lang = this.FormatFreeTargetLanguage(targetLanguage),
source_lang_user_selected = this.FormatSourceLanguage(sourceLanguage),
},
commonJobParams = new
{
wasSpoken = false,
transcribe_as = string.Empty,
},
texts = new[]
{
new
{
text,
request_alternatives = 3,
},
},
timestamp,
},
id,
};
var requestBodyText = JsonConvert.SerializeObject(requestBody);
// Adding spaces to the JSON string based on the ID to adhere to DeepL's request formatting rules
if ((id + 5) % 29 == 0 || (id + 3) % 13 == 0)
{
requestBodyText = requestBodyText.Replace("\"method\":\"", "\"method\" : \"");
}
else
{
requestBodyText = requestBodyText.Replace("\"method\":\"", "\"method\": \"");
}
var response = await this.httpClient.PostAsync(FreeEndpoint, new StringContent(
requestBodyText,
Encoding.UTF8,
"application/json"));
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
var deepLResponse = JsonConvert.DeserializeObject<DeepLResponse>(jsonString);
var finalTranslatedText = deepLResponse.Result.Texts[0].Text;
this.pluginLog.Debug($"FinalTranslatedText: {finalTranslatedText}");
return finalTranslatedText;
}
else
{
this.pluginLog.Warning($"DeepLTranslator FreeTranslateAsync error: {response.StatusCode}");
return text;
}
}
catch (Exception exception)
{
this.pluginLog.Warning($"DeepLTranslator FreeTranslateAsync: {exception.Message}");
return text;
}
}
private string FormatSourceLanguage(string source)
{
switch (source)
{
case "Japanese":
return "JA";
case "English":
return "EN";
case "German":
return "DE";
case "French":
return "FR";
default:
return "EN";
}
}
private string FormatTargetLanguage(string source)
{
switch (source)
{
case "en":
return "EN-US";
case "no":
return "NB";
case "pt":
return "PT-BR";
case "zh-CN":
return "ZH";
case "pt-PT":
return "PT-PT";
case "it":
return "IT";
default:
return source.ToUpper();
}
}
private string FormatFreeTargetLanguage(string source)
{
switch (source)
{
case "en":
return "EN-US";
case "no":
return "NB";
case "pt":
return "PT-BR";
case "zh-CN":
return "ZH";
case "pt-PT":
return "PT-PT";
case "it":
return "IT";
default:
return source.ToUpper();
}
}
}
public class DeepLResponse
{
public string Id { get; set; }
public string Jsonrpc { get; set; }
public DeepLResult Result { get; set; }
}
public class DeepLResult
{
public DeepLTextResult[] Texts { get; set; }
public string Lang { get; set; }
}
public class DeepLTextResult
{
public string Text { get; set; }
}
}