forked from intento/intento-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntentoAiTextTranslate.cs
467 lines (394 loc) · 18.4 KB
/
IntentoAiTextTranslate.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
namespace IntentoSDK
{
public class IntentoAiTextTranslate
{
Intento intento;
IntentoAiText parent;
public IntentoAiTextTranslate(IntentoAiText parent)
{
this.parent = parent;
this.intento = parent.Intento;
}
public Intento Intento
{ get { return intento; } }
public IntentoAiText Parent
{ get { return parent; } }
public dynamic Fulfill(object text, string to, string from = null, string provider = null,
bool async = false, bool wait_async = false, string format = null, object auth = null,
string custom_model = null, string glossary = null,
object pre_processing = null, object post_processing = null,
bool failover = false, object failover_list = null, string routing = null, bool trace = false)
{
Task<dynamic> taskReadResult = Task.Run<dynamic>(async () => await this.FulfillAsync(text, to, from: from, provider: provider,
async: async, wait_async: wait_async, format: format, auth: auth,
custom_model: custom_model, glossary: glossary,
pre_processing: pre_processing, post_processing: post_processing,
failover: failover, failover_list: failover_list, routing: routing, trace: trace));
return taskReadResult.Result;
}
async public Task<dynamic> FulfillAsync(object text, string to, string from = null, string provider = null,
bool async = false, bool wait_async = false, string format = null, object auth = null,
string custom_model = null, string glossary = null,
object pre_processing = null, object post_processing = null,
bool failover = false, object failover_list = null, string routing = null, bool trace = false, bool deserialize_text=false)
{
dynamic preProcessingJson = GetJson(pre_processing, "pre_processing");
dynamic postProcessingJson = GetJson(post_processing, "post_processing");
dynamic json = new JObject();
// ------ context section
dynamic context = new JObject();
// text
if (text == null)
context.text = "";
else if (text is IEnumerable<string>)
context.text = GetJson(((IEnumerable<string>)text).Select(i => i == null ? "" : i), "text");
else
context.text = GetJson(text.ToString(), "text") ?? "";
// to
context.to = to;
// from
if (!string.IsNullOrWhiteSpace(from))
context.from = from;
// format
if (!string.IsNullOrWhiteSpace(format))
context.format = format;
// custom_model
if (!string.IsNullOrWhiteSpace(custom_model))
context.category = custom_model;
// glossary
if (!string.IsNullOrWhiteSpace(glossary))
context.glossary = glossary;
json.context = context;
// ----- service section
dynamic service = new JObject();
// provider
if (!string.IsNullOrWhiteSpace(provider))
service.provider = provider;
// async parameter
if (async)
service.async = true;
// auth parameter
service.auth = GetJson(auth, "auth");
// routing
if (!string.IsNullOrEmpty(routing))
service.routing = routing;
// pre-post processing paramters
if (preProcessingJson != null || postProcessingJson != null)
{
dynamic processing = new JObject();
if (preProcessingJson != null)
processing.pre = preProcessingJson;
if (postProcessingJson != null)
processing.post = postProcessingJson;
service.processing = processing;
}
// failover parameters
if (failover)
{
service.failover = true;
JArray failoverJson;
if (failover_list != null)
{
if (failover_list is string)
failoverJson = JArray.Parse((string)failover_list);
else if (failover_list is JArray)
failoverJson = (JArray)failover_list;
else
throw new IntentoInvalidParameterException("failover_list", "need to json-list-string or Newtonsoft JArray");
service.failover_list = failover_list;
}
}
json.service = service;
// Call to Intento API and get json result
HttpConnector conn = new HttpConnector(Intento);
string url = "ai/text/translate";
if (trace)
url += "?trace=true";
dynamic jsonResult = await conn.PostAsync(url, json);
if (async && wait_async)
{ // async opertation (in terms of IntentoApi) and we need to wait result of it
string id = jsonResult.id;
// In case of Sandbox key and some errors in parameters request to IntentoAPI may return:
// 1. id: async operation started
// 2. result of translation: Sandcox key
// 3. error: validation of arameters failed (like request to translate html with provider with no such capabilities)
if (id == null)
// Not a (1) - return result immediately, nothing to wait
return jsonResult;
jsonResult = await Intento.WaitAsyncJobAsync(id);
}
return jsonResult;
}
private dynamic GetJson(object data, string name)
{
// Convert data to json.
// String is deserialized in case it has a for of json list or dict.
// data=="" is trated as null
if (data == null)
return null;
else if (data is string)
{
string z = ((string)data).Trim();
if (string.IsNullOrEmpty(z))
return null;
try
{
if (z[0] == '[')
return JArray.Parse(z);
if (z[0] == '{')
return JObject.Parse(z);
}
catch { }
return (string)data;
}
else if (data is JObject)
return (JObject)data;
else if (data is JArray)
return (JArray)data;
else if (data is IDictionary<string, string>)
return (JObject.FromObject((Dictionary<string, string>)data));
else if (data is IEnumerable<string>)
return (JArray.FromObject((IEnumerable<string>)data));
throw new IntentoInvalidParameterException(name, "need to be null or string or json-string or Newtonsoft JObject/JArray");
}
/// <summary>
/// Details of the models stored by the provider
/// </summary>
/// <param name="provider">Provider id</param>
/// <param name="credential_id">Credential id</param>
/// <param name="additionalParams">additional url params</param>
/// <returns>dynamic (json) with requested information</returns>
public IList<dynamic> Models(string provider, Dictionary<string, string> credential_id, string additionalParams = null)
{
Task<dynamic> taskReadResult = Task.Run<dynamic>(async () =>
await this.ModelsAsync(provider, credential_id, additionalParams: additionalParams));
return taskReadResult.Result;
}
/// <summary>
/// Details of the models stored by the provider
/// </summary>
/// <param name="provider">Provider id</param>
/// <param name="credential_id">Credential id</param>
/// <param name="additionalParams">additional url params</param>
/// <returns>dynamic (json) with requested information</returns>
async public Task<IList<dynamic>> ModelsAsync(string providerId, Dictionary<string, string> credential_id, string additionalParams = null)
{
string path = string.Format("ai/text/translate/models?provider={0}", providerId);
if (credential_id != null)
{
string json;
if (credential_id.Count != 0)
{
if (credential_id.Count == 1 && credential_id.ContainsKey("credential_id"))
json = credential_id["credential_id"];
else
{
json = JsonConvert.SerializeObject(credential_id, Formatting.Indented);
json = HttpUtility.UrlEncode(json);
}
path += String.Format("&credential_id={0}", json);
}
}
if (additionalParams != null)
path += additionalParams;
// Call to Intento API and get json result
HttpConnector conn = new HttpConnector(Intento);
dynamic jsonResult = await conn.GetAsync(path);
List<dynamic> models = new List<dynamic>();
foreach (dynamic model in ((JContainer)jsonResult).First.First)
models.Add(model);
return models;
}
/// <summary>
/// Details of the glossaries stored by the provider
/// </summary>
/// <param name="provider">Provider id</param>
/// <param name="credential_id">Credential id</param>
/// <param name="additionalParams">additional url params</param>
/// <returns>dynamic (json) with requested information</returns>
public IList<dynamic> Glossaries(string provider, Dictionary<string, string> credential_id, string additionalParams = null)
{
Task<dynamic> taskReadResult = Task.Run<dynamic>(async () =>
await this.GlossariesAsync(provider, credential_id: credential_id, additionalParams: additionalParams));
return taskReadResult.Result;
}
/// <summary>
/// Details of the glossaries stored by the provider
/// </summary>
/// <param name="provider">Provider id</param>
/// <param name="credential_id">Credential id</param>
/// <param name="additionalParams">additional url params</param>
/// <returns>dynamic (json) with requested information</returns>
async public Task<IList<dynamic>> GlossariesAsync(string providerId, Dictionary<string, string> credential_id, string additionalParams = null)
{
string path = string.Format("ai/text/translate/glossaries?provider={0}", providerId);
if (credential_id != null)
{
string json;
if (credential_id.Count != 0)
{
if (credential_id.Count == 1 && credential_id.ContainsKey("credential_id"))
json = credential_id["credential_id"];
else
{
json = JsonConvert.SerializeObject(credential_id, Formatting.Indented);
json = HttpUtility.UrlEncode(json);
}
path += String.Format("&credential_id={0}", json);
}
}
if (additionalParams != null)
path += additionalParams;
// Call to Intento API and get json result
HttpConnector conn = new HttpConnector(Intento);
dynamic jsonResult = await conn.GetAsync(path);
List<dynamic> glossaries = new List<dynamic>();
foreach (dynamic glossary in ((JContainer)jsonResult).First.First)
glossaries.Add(glossary);
return glossaries;
}
/// <summary>
/// Get a list of available delegated credentials
/// </summary>
/// <param name="additionalParams">additional url params</param>
/// <returns>dynamic (json) with requested information</returns>
public IList<dynamic> DelegatedCredentials(string additionalParams = null)
{
Task<dynamic> taskReadResult = Task.Run<dynamic>(async () =>
await this.DelegatedCredentialsAsync(additionalParams: additionalParams));
return taskReadResult.Result;
}
/// <summary>
/// Get a list of available delegated credentials
/// </summary>
/// <param name="additionalParams">additional url params</param>
/// <returns>dynamic (json) with requested information</returns>
async public Task<IList<dynamic>> DelegatedCredentialsAsync(string additionalParams = null)
{
string path = "delegated_credentials";
if (additionalParams != null)
path += additionalParams;
// Call to Intento API and get json result
HttpConnector conn = new HttpConnector(Intento);
dynamic jsonResult = await conn.GetAsync(path);
List<dynamic> credentials = new List<dynamic>();
foreach (dynamic credential in jsonResult)
credentials.Add(credential);
return credentials;
}
/// <summary>
/// Detailed information on provider features
/// </summary>
/// <param name="provider">Provider id</param>
/// <param name="additionalParams">additional url params</param>
/// <returns>dynamic (json) with requested information</returns>
public dynamic Provider(string provider, string additionalParams = null)
{
Task<dynamic> taskReadResult = Task.Run<dynamic>(async () => await this.ProviderAsync(provider, additionalParams:additionalParams));
return taskReadResult.Result;
}
/// <summary>
/// Detailed information on provider features
/// </summary>
/// <param name="provider">Provider id</param>
/// <returns>dynamic (json) with requested information</returns>
async public Task<dynamic> ProviderAsync(string providerId, string additionalParams = null)
{
string path = string.Format("ai/text/translate/{0}", providerId);
if (additionalParams != null)
path += additionalParams;
// Call to Intento API and get json result
HttpConnector conn = new HttpConnector(Intento);
dynamic jsonResult = await conn.GetAsync(path);
return jsonResult;
}
public IList<dynamic> Providers(string to = null, string from = null, bool lang_detect = false, bool bulk = false,
Dictionary<string, string> filter = null)
{
Task<IList<dynamic>> taskReadResult = Task.Run<IList<dynamic>>(async () =>
await this.ProvidersAsync(to: to, from: from, lang_detect: lang_detect, bulk: bulk, filter: filter));
return taskReadResult.Result;
}
async public Task<IList<dynamic>> ProvidersAsync(string to = null, string from = null, bool lang_detect = false, bool bulk = false,
Dictionary<string, string> filter = null)
{
Dictionary<string, string> f = new Dictionary<string, string>(filter);
if (!string.IsNullOrEmpty(to))
f["to"] = to;
if (!string.IsNullOrEmpty(from))
f["from"] = from;
if (lang_detect)
f["lang_detect"] = "true";
if (bulk)
f["bulk"] = "true";
List<string> p = new List<string>();
foreach(KeyValuePair<string, string> pair in f)
p.Add(string.Format("{0}={1}", pair.Key, System.Web.HttpUtility.UrlEncode(pair.Value)));
string url = "ai/text/translate";
if (p.Count != 0)
url += "?" + string.Join("&", p);
// Call to Intento API and get json result
HttpConnector conn = new HttpConnector(Intento);
dynamic jsonResult = await conn.GetAsync(url);
List<dynamic> providers = new List<dynamic>();
foreach (dynamic providerInfo in jsonResult)
providers.Add(providerInfo);
return providers;
}
public IList<dynamic> Languages()
{
Task<IList<dynamic>> taskReadResult = Task.Run<IList<dynamic>>(async () => await this.LanguagesAsync());
return taskReadResult.Result;
}
async public Task<IList<dynamic>> LanguagesAsync()
{
string url = "ai/text/translate/languages";
// Call to Intento API and get json result
HttpConnector conn = new HttpConnector(Intento);
dynamic jsonResult = await conn.GetAsync(url);
List<dynamic> languages = new List<dynamic>();
foreach (dynamic languageInfo in jsonResult)
languages.Add(languageInfo);
return languages;
}
public IList<IList<string>> ProviderLanguagePairs(string providerId)
{
Task<IList<IList<string>>> taskReadResult = Task.Run<IList<IList<string>>>(async () => await this.ProviderLanguagePairsAsync(providerId));
return taskReadResult.Result;
}
async public Task<IList<IList<string>>> ProviderLanguagePairsAsync(string providerId)
{
dynamic providerInfo = await ProviderAsync(providerId);
List<IList<string>> res = new List<IList<string>>();
dynamic languages = providerInfo.languages;
dynamic symmetric = languages.symmetric;
if (symmetric != null)
{
foreach (string l1 in symmetric)
foreach (string l2 in symmetric)
if (l1 != l2)
res.Add(new List<string> { l1, l2 });
}
dynamic pairs = languages.pairs;
if (pairs != null)
{
foreach (dynamic pair in pairs)
res.Add(new List<string> { (string)pair.from, (string)pair.to });
}
return res;
}
}
}