/
translator.ts
330 lines (281 loc) · 12.4 KB
/
translator.ts
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as request from 'request-promise-native';
export interface TranslateArrayOptions {
texts: string[]; from: string;
to: string;
contentType?: string;
category?: string;
}
export interface TranslationResult {
translatedText: string;
}
export interface TranslationRequest {
text: string;
}
export class MicrosoftTranslator {
private postProcessor: TranslatorPostProcessor;
constructor(private apiKey: string, noTranslatePatterns?: { [id: string]: string[] }, wordDictionary?: { [id: string]: string }) {
this.apiKey = apiKey;
this.postProcessor = new TranslatorPostProcessor(noTranslatePatterns, wordDictionary);
}
public detect = async (text: string): Promise<object> => {
const uri: any = "https://api.cognitive.microsofttranslator.com/detect?api-version=3.0";
let translationRequest = {
text: text
};
const response = await request({
url: uri,
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': this.apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify([translationRequest]),
});
return JSON.parse(response);
};
public translateArray = async (options: TranslateArrayOptions): Promise<object> => {
try {
const { from, to, texts } = options;
let orgTexts = [];
let translationRequests = [];
let results = [];
texts.forEach((text, index) => {
let normalizedText = text.trim();
orgTexts.push(normalizedText);
texts[index] = normalizedText;
let translationRequest = {
text: normalizedText
};
translationRequests.push(translationRequest);
});
let uri: any = `https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&includeAlignment=true&includeSentenceLength=true&from=${from}&to=${to}`;
const response = await request({
url: uri,
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': this.apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify(translationRequests),
});
const translations = JSON.parse(response);
translations.forEach((traslationModel, index) => {
let translation = traslationModel.translations[0].text;
if (traslationModel.translations[0].alignment) {
let alignment = traslationModel.translations[0].alignment.proj;
translation = this.postProcessor.postprocessTranslation(orgTexts[index], alignment, translation, from);
}
results.push({ translatedText: translation });
});
return results;
} catch (e) {
switch (e.statusCode) {
case 401:
throw new Error('Cognitive Authentication Failed');
default:
throw new Error('Internal Error');
}
}
};
}
/**
* @private
*/
class TranslatorPostProcessor {
noTranslatePatterns: { [languageId: string]: string[] };
wordDictionary: { [id: string]: string };
constructor(noTranslatePatterns?: { [languageId: string]: string[] }, wordDictionary?: { [id: string]: string }) {
this.noTranslatePatterns = {};
this.wordDictionary = wordDictionary;
if (wordDictionary) {
Object.keys(this.wordDictionary).forEach(word => {
if (word !== word.toLowerCase()) {
Object.defineProperty(this.wordDictionary, word.toLowerCase(),
Object.getOwnPropertyDescriptor(this.wordDictionary, word));
delete this.wordDictionary[word];
}
});
}
if (noTranslatePatterns) {
for (const key in noTranslatePatterns) {
noTranslatePatterns[key].forEach((pattern, index) => {
if (!(key in this.noTranslatePatterns)) {
this.noTranslatePatterns[key] = [];
}
if (pattern.indexOf('(') == -1) {
pattern = `(${pattern})`;
}
this.noTranslatePatterns[key][index] = pattern;
});
}
}
}
private join(delimiter: string, words: string[]): string {
return words.join(delimiter).replace(/[ ]?'[ ]?/g, "'").trim();
}
private splitSentence(sentence: string, alignments: string[], isSrcSentence = true): string[] {
const words = sentence.split(' ');
const lastWord = words[words.length - 1];
if (".,:;?!".indexOf(lastWord[lastWord.length - 1]) !== -1) {
words[words.length - 1] = lastWord.substr(0, lastWord.length - 1);
}
let alignSplitWrds: string[] = [];
const outWrds: string[] = [];
let wrdIndexInAlignment = 1;
if (isSrcSentence) {
wrdIndexInAlignment = 0;
} else {
alignments.sort((a, b) => {
const aIndex = parseInt(a.split('-')[wrdIndexInAlignment].split(':')[0]);
const bIndex = parseInt(b.split('-')[wrdIndexInAlignment].split(':')[0]);
if (aIndex <= bIndex) {
return -1;
} else {
return 1;
}
});
}
const sentenceWithoutSpaces = sentence.replace(/\s/g, '');
alignments.forEach(alignData => {
alignSplitWrds = outWrds;
const wordIndexes = alignData.split('-')[wrdIndexInAlignment];
const startIndex = parseInt(wordIndexes.split(':')[0]);
const length = parseInt(wordIndexes.split(':')[1]) - startIndex + 1;
const wrd = sentence.substr(startIndex, length);
let newWrds: string[] = new Array(outWrds.length + 1);
if (newWrds.length > 1) {
newWrds = alignSplitWrds.slice();
}
newWrds[outWrds.length] = wrd;
const subSentence = this.join("", newWrds);
if (sentenceWithoutSpaces.indexOf(subSentence) !== -1) {
outWrds.push(wrd);
}
});
alignSplitWrds = outWrds;
if (this.join("", alignSplitWrds) == this.join("", words)) {
return alignSplitWrds;
} else {
return words;
}
}
private wordAlignmentParse(alignments: string[], srcWords: string[], trgWords: string[]): { [id: number]: number } {
let alignMap: { [id: number]: number } = {};
let sourceMessage = this.join(" ", srcWords);
let trgMessage = this.join(" ", trgWords);
alignments.forEach(alignData => {
let wordIndexes = alignData.split('-');
let srcStartIndex = parseInt(wordIndexes[0].split(':')[0]);
let srcLength = parseInt(wordIndexes[0].split(':')[1]) - srcStartIndex + 1;
let srcWrd = sourceMessage.substr(srcStartIndex, srcLength);
let srcWrdIndex = srcWords.findIndex(wrd => wrd == srcWrd);
let trgstartIndex = parseInt(wordIndexes[1].split(':')[0]);
let trgLength = parseInt(wordIndexes[1].split(':')[1]) - trgstartIndex + 1;
let trgWrd = trgMessage.substr(trgstartIndex, trgLength);
let trgWrdIndex = trgWords.findIndex(wrd => wrd == trgWrd);
if (srcWrdIndex !== -1 && trgWrdIndex !== -1) {
alignMap[srcWrdIndex] = trgWrdIndex;
}
});
return alignMap;
}
private keepSrcWrdInTranslation(alignment: { [id: number]: number }, sourceWords: string[], targetWords: string[], srcWrdIndex: number) {
if (!(typeof alignment[srcWrdIndex] === "undefined")) {
targetWords[alignment[srcWrdIndex]] = sourceWords[srcWrdIndex];
}
return targetWords;
}
/**
* postprocessTranslation is the method responsible for applying customizations on the raw translation for example :
* applying patterns customization and custom user configured vocab dictionary
*
* @param sourceMessage
* @param alignment
* @param targetMessage
* @param languageId
*/
public postprocessTranslation(sourceMessage: string, alignment: string, targetMessage: string, languageId: string): string {
let numericMatches = sourceMessage.match(/[0-9]+/g);
let containsNum = numericMatches !== null;
if ((!containsNum && (!this.noTranslatePatterns || !this.noTranslatePatterns[languageId] || this.noTranslatePatterns[languageId].length == 0) && !this.wordDictionary) || alignment.trim() === '') {
return targetMessage;
}
let toBeReplaced: string[] = [];
if (this.noTranslatePatterns[languageId]) {
this.noTranslatePatterns[languageId].forEach(pattern => {
let regExp = new RegExp(pattern, "i");
let matches = sourceMessage.match(regExp);
if (matches !== null) {
toBeReplaced.push(pattern);
}
});
}
let toBeReplacedByDictionary: string[] = [];
if (this.wordDictionary) {
Object.keys(this.wordDictionary).forEach(word => {
if (sourceMessage.toLowerCase().indexOf(word.toLowerCase()) !== -1) {
toBeReplacedByDictionary.push(word);
}
});
}
let alignments = alignment.trim().split(' ');
let srcWords = this.splitSentence(sourceMessage, alignments);
let trgWords = this.splitSentence(targetMessage, alignments, false);
let alignMap = this.wordAlignmentParse(alignments, srcWords, trgWords);
if (toBeReplaced.length > 0) {
toBeReplaced.forEach(pattern => {
let regExp = new RegExp(pattern, "i");
let match = regExp.exec(sourceMessage);
let noTranslateStartChrIndex = match.index + match[0].indexOf(match[1]);
let noTranslateMatchLength = match[1].length;
let wrdIndx = 0;
let chrIndx = 0;
let newChrLengthFromMatch = 0;
let srcIndx = -1;
let newNoTranslateArrayLength = 1;
const sourceMessageCharacters = sourceMessage.split('');
srcWords.forEach(wrd => {
if (chrIndx == noTranslateStartChrIndex) {
srcIndx = wrdIndx;
}
if (srcIndx !== -1) {
if (newChrLengthFromMatch + srcWords[wrdIndx].length >= noTranslateMatchLength) {
return;
}
newNoTranslateArrayLength++;
newChrLengthFromMatch += srcWords[wrdIndx].length;
}
if (chrIndx + wrd.length < sourceMessageCharacters.length && sourceMessageCharacters[chrIndx + wrd.length] === ' ') {
chrIndx += wrd.length + 1;
}
else {
chrIndx += wrd.length;
}
wrdIndx++;
if (srcIndx === -1) {
return;
}
});
let wrdNoTranslate = srcWords.slice(srcIndx, srcIndx + newNoTranslateArrayLength)
wrdNoTranslate.forEach(srcWrds => {
trgWords = this.keepSrcWrdInTranslation(alignMap, srcWords, trgWords, srcIndx);
srcIndx++;
});
});
}
if (this.wordDictionary) {
srcWords.forEach((wrd, index) => {
if (wrd.toLowerCase() in this.wordDictionary) {
const replacementWord = this.wordDictionary[wrd.toLowerCase()];
trgWords[alignMap[index]] = replacementWord;
} else if (wrd.toUpperCase() in this.wordDictionary) {
const replacementWord = this.wordDictionary[wrd.toUpperCase()];
trgWords[alignMap[index]] = replacementWord;
}
});
}
return this.join(" ", trgWords);
}
}