-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TranslationEngineServiceV1.cs
304 lines (288 loc) · 15.1 KB
/
TranslationEngineServiceV1.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
namespace EchoTranslationEngine;
public class TranslationEngineServiceV1(BackgroundTaskQueue taskQueue, HealthCheckService healthCheckService) : TranslationEngineApi.TranslationEngineApiBase
{
private static readonly Empty Empty = new();
private readonly BackgroundTaskQueue _taskQueue = taskQueue;
private readonly HealthCheckService _healthCheckService = healthCheckService;
public override Task<Empty> Create(CreateRequest request, ServerCallContext context)
{
if (request.SourceLanguage != request.TargetLanguage)
{
Status status = new Status(StatusCode.InvalidArgument, "Source and target languages must be the same");
throw new RpcException(status);
}
return Task.FromResult(Empty);
}
public override Task<Empty> Delete(DeleteRequest request, ServerCallContext context)
{
return Task.FromResult(Empty);
}
public override Task<TranslateResponse> Translate(TranslateRequest request, ServerCallContext context)
{
string[] tokens = request.Segment.Split();
var response = new TranslateResponse
{
Results =
{
new TranslationResult
{
Translation = request.Segment,
SourceTokens = { tokens },
TargetTokens = { tokens },
Confidences = { Enumerable.Repeat(1.0, tokens.Length) },
Sources =
{
Enumerable.Repeat(
new TranslationSources { Values = { TranslationSource.Primary } },
tokens.Length
)
},
Alignment =
{
Enumerable
.Range(0, tokens.Length)
.Select(i => new AlignedWordPair { SourceIndex = i, TargetIndex = i })
},
Phrases =
{
new Phrase
{
SourceSegmentStart = 0,
SourceSegmentEnd = tokens.Length,
TargetSegmentCut = tokens.Length
}
}
}
}
};
return Task.FromResult(response);
}
public override async Task<Empty> StartBuild(StartBuildRequest request, ServerCallContext context)
{
await _taskQueue.QueueBackgroundWorkItemAsync(
async (services, cancellationToken) =>
{
var client = services.GetRequiredService<TranslationPlatformApi.TranslationPlatformApiClient>();
await client.BuildStartedAsync(
new BuildStartedRequest { BuildId = request.BuildId },
cancellationToken: cancellationToken
);
try
{
using (var call = client.InsertPretranslations(cancellationToken: cancellationToken))
{
foreach (Corpus corpus in request.Corpora)
{
if (!corpus.PretranslateAll && corpus.PretranslateTextIds.Count == 0)
continue;
var sourceFiles = corpus.SourceFiles
.Where(
f =>
(corpus.PretranslateAll || corpus.PretranslateTextIds.Contains(f.TextId))
&& f.Format == FileFormat.Text
)
.ToDictionary(f => f.TextId, f => f.Location);
var targetFiles = corpus.TargetFiles
.Where(
f =>
(corpus.PretranslateAll || corpus.PretranslateTextIds.Contains(f.TextId))
&& f.Format == FileFormat.Text
)
.ToDictionary(f => f.TextId, f => f.Location);
foreach (KeyValuePair<string, string> sourceFile in sourceFiles)
{
string[] sourceLines = await File.ReadAllLinesAsync(
sourceFile.Value,
cancellationToken
);
if (targetFiles.TryGetValue(sourceFile.Key, out string? targetPath))
{
string[] targetLines = await File.ReadAllLinesAsync(targetPath, cancellationToken);
bool isTabSeparated = (sourceLines.Length > 0) && sourceLines[0].Contains('/');
if (!isTabSeparated)
{
int lineNum = 1;
foreach (
(string sourceLine, string targetLine) in sourceLines
.Select(l => l.Trim())
.Zip(targetLines.Select(l => l.Trim()))
)
{
if (sourceLine.Length > 0 && targetLine.Length == 0)
{
await call.RequestStream.WriteAsync(
new InsertPretranslationRequest
{
EngineId = request.EngineId,
CorpusId = corpus.Id,
TextId = sourceFile.Key,
Refs = { $"{sourceFile.Key}:{lineNum}" },
Translation = sourceLine
},
cancellationToken
);
}
lineNum++;
}
}
else
{
var sourceLinesDict = sourceLines.ToDictionary(
l => l.Split('\t')[0].Trim(),
l => l.Split('\t')[1].Trim()
);
var targetLinesDict = targetLines.ToDictionary(
l => l.Split('\t')[0].Trim(),
l => l.Contains('\t') ? l.Split('\t')[1].Trim() : string.Empty
);
foreach (KeyValuePair<string, string> targetLineKVPair in targetLinesDict)
{
string? sourceLine = null;
sourceLinesDict.TryGetValue(targetLineKVPair.Key, out sourceLine);
sourceLine ??= string.Empty;
string? targetLine = targetLineKVPair.Value;
if (sourceLine.Length > 0 && targetLine.Length == 0)
{
await call.RequestStream.WriteAsync(
new InsertPretranslationRequest
{
EngineId = request.EngineId,
CorpusId = corpus.Id,
TextId = sourceFile.Key,
Refs = { $"{sourceFile.Key}:{targetLineKVPair.Key}" },
Translation = sourceLine
},
cancellationToken
);
}
}
}
}
else
{
bool isTabSeparated = (sourceLines.Length > 0) && sourceLines[0].Contains('/');
if (!isTabSeparated)
{
int lineNum = 1;
foreach (string sourceLine in sourceLines.Select(l => l.Trim()))
{
if (sourceLine.Length > 0)
{
await call.RequestStream.WriteAsync(
new InsertPretranslationRequest
{
EngineId = request.EngineId,
CorpusId = corpus.Id,
TextId = sourceFile.Key,
Refs = { $"{sourceFile.Key}:{lineNum}" },
Translation = sourceLine
},
cancellationToken
);
}
lineNum++;
}
}
else
{
foreach (string sourceLine in sourceLines.Select(l => l.Trim()))
{
if (sourceLine.Length > 0)
{
await call.RequestStream.WriteAsync(
new InsertPretranslationRequest
{
EngineId = request.EngineId,
CorpusId = corpus.Id,
TextId = sourceFile.Key,
Refs = { $"{sourceFile.Key}:{sourceLine.Split('\t')[0]}" },
Translation = sourceLine.Contains('\t')
? sourceLine.Split('\t')[1].Trim()
: string.Empty
},
cancellationToken
);
}
}
}
}
}
}
await call.RequestStream.CompleteAsync();
await call;
}
await client.BuildCompletedAsync(
new BuildCompletedRequest { BuildId = request.BuildId, Confidence = 1.0 },
cancellationToken: CancellationToken.None
);
}
catch (OperationCanceledException)
{
await client.BuildCanceledAsync(
new BuildCanceledRequest { BuildId = request.BuildId },
cancellationToken: CancellationToken.None
);
}
catch (Exception e)
{
await client.BuildFaultedAsync(
new BuildFaultedRequest { BuildId = request.BuildId, Message = e.Message },
cancellationToken: CancellationToken.None
);
}
}
);
return Empty;
}
public override Task<Empty> TrainSegmentPair(TrainSegmentPairRequest request, ServerCallContext _)
{
return Task.FromResult(Empty);
}
public override Task<GetWordGraphResponse> GetWordGraph(GetWordGraphRequest request, ServerCallContext _)
{
var tokens = request.Segment.Split();
return Task.FromResult(
new GetWordGraphResponse
{
WordGraph = new WordGraph
{
InitialStateScore = 0.0,
SourceTokens = { tokens },
Arcs =
{
Enumerable
.Range(0, tokens.Length - 1)
.Select(
index =>
new WordGraphArc
{
PrevState = index,
NextState = index + 1,
Score = 1.0,
TargetTokens = { tokens[index] },
Confidences = { 1.0 },
SourceSegmentStart = index,
SourceSegmentEnd = index + 1,
Alignment =
{
new AlignedWordPair { SourceIndex = 0, TargetIndex = 0 }
}
}
)
},
FinalStates = { tokens.Length }
}
}
);
}
public override Task<GetQueueSizeResponse> GetQueueSize(GetQueueSizeRequest request, ServerCallContext context)
{
return Task.FromResult(new GetQueueSizeResponse { Size = 0 });
}
public override async Task<HealthCheckResponse> HealthCheck(Empty request, ServerCallContext context)
{
HealthReport healthReport = await _healthCheckService.CheckHealthAsync();
HealthCheckResponse healthCheckResponse = WriteGrpcHealthCheckResponse.Generate(healthReport);
return healthCheckResponse;
}
}