Frames

Untitled

0
1const languages = require('./languages');
2const {
3 validateText,
4 validateSourceLanguage,
5 validateTargetLanguage,
6 validateSourceTargetLanguage,
7 validateBeginning,
8} = require('./validators');
9
10const {
11 splitSentences,
12 getTranslation,
13 getAlternatives,
14} = require('./deepl-api-helper');
15const { EOL } = require('os');
16
17function detectLanguage(text) {
18 return translate(text, 'EN').then(({ resolvedSourceLanguage }) => {
19 return {
20 languageCode: resolvedSourceLanguage,
21 languageName: resolvedSourceLanguage
22 .split(',')
23 .map(code => languages[code])
24 .join(','),
25 };
26 });
27}
28
29function validateInputs(validationArray) {
30 return Promise.all(validationArray).then(validationResults => {
31 const errors = validationResults
32 .filter(validationResult => validationResult)
33 .join('\n');
34
35 return errors.length
36 ? Promise.reject(
37 new Error(
38 `Input parameter validation failed with error(s): ${errors}`
39 )
40 )
41 : Promise.resolve('');
42 });
43}
44
45function translate(text, targetLanguage, sourceLanguage = 'auto') {
46 return validateInputs([
47 validateText(text),
48 validateSourceLanguage(sourceLanguage),
49 validateTargetLanguage(targetLanguage),
50 validateSourceTargetLanguage(sourceLanguage, targetLanguage),
51 ])
52 .then(valid => splitSentences(text.split(EOL), sourceLanguage))
53 .then(transformSplitSentencesResponse)
54 .then(([paragraphs, resolvedSourceLanguage]) => {
55 return Promise.all(
56 paragraphs.map(
57 paragraph =>
58 paragraph.length === 0
59 ? []
60 : getTranslation(
61 paragraph,
62 targetLanguage,
63 resolvedSourceLanguage || 'auto'
64 ).then(transformTranslationResponse)
65 )
66 ).then(translatedParagraphs => ({
67 targetLanguage,
68 resolvedSourceLanguage: translatedParagraphs
69 .map(paragraph => paragraph[1])
70 .reduce(
71 (unique, current) => [
72 ...unique,
73 unique.indexOf(current) < 0 && current,
74 ],
75 []
76 )
77 .filter(lang => lang)
78 .join(','),
79 translation: translatedParagraphs
80 .map(([paragraph]) => paragraph || '')
81 .join(EOL),
82 }));
83 });
84}
85
86function translateWithAlternatives(
87 text,
88 targetLanguage,
89 sourceLanguage = 'auto',
90 beginning
91) {
92 return validateInputs([
93 validateText(text),
94 validateSourceLanguage(sourceLanguage),
95 validateTargetLanguage(targetLanguage),
96 validateSourceTargetLanguage(sourceLanguage, targetLanguage),
97 ])
98 .then(valid =>
99 getTranslation([text], targetLanguage, sourceLanguage, beginning)
100 )
101 .then(({ result: { source_lang, translations: [{ beams }] } }) => ({
102 targetLanguage,
103 resolvedSourceLanguage: source_lang,
104 translation: beams[0].postprocessed_sentence,
105 translationAlternatives: beams.map(
106 ({ postprocessed_sentence }) => postprocessed_sentence
107 ),
108 }));
109}
110
111function wordAlternatives(text, targetLanguage, sourceLanguage, beginning) {
112 return validateInputs([
113 validateText(text),
114 validateSourceLanguage(sourceLanguage),
115 validateTargetLanguage(targetLanguage),
116 validateSourceTargetLanguage(sourceLanguage, targetLanguage),
117 validateBeginning(beginning),
118 ])
119 .then(valid =>
120 getAlternatives(text, targetLanguage, sourceLanguage, beginning)
121 )
122 .then(res => {
123 return {
124 targetLanguage: res.result.target_lang,
125 resolvedSourceLanguage: res.result.source_lang,
126 alternatives: res.result.translations[0].beams.map(alt => {
127 return alt.postprocessed_sentence;
128 }),
129 };
130 });
131}
132
133function transformTranslationResponse(response) {
134 try {
135 const {
136 result: {
137 target_lang: targetLanguage,
138 source_lang: resolvedSourceLanguage,
139 translations,
140 },
141 } = response;
142
143 const translatedSentences = translations.map(
144 ({ beams: [{ postprocessed_sentence: translation }] }) => translation
145 );
146
147 return [translatedSentences.join(' '), resolvedSourceLanguage];
148 } catch (error) {
149 throw new Error(
150 `Unexpected error when parsing deepl translation response: ${JSON.stringify(
151 response
152 )}`
153 );
154 }
155}
156
157function transformSplitSentencesResponse(response) {
158 try {
159 const {
160 result: { splitted_texts: texts, lang_is_confident, lang },
161 } = response;
162
163 return [texts, lang_is_confident && lang];
164 } catch (error) {
165 throw new Error(
166 `Unexpected error when parsing deepl split sentence response: ${JSON.stringify(
167 response
168 )}`
169 );
170 }
171}
172
173module.exports = {
174 translate,
175 translateWithAlternatives,
176 detectLanguage,
177 wordAlternatives,
178};
179