forked from mayeaux/generate-subtitles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate-files-api.js
63 lines (49 loc) · 1.81 KB
/
translate-files-api.js
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
const translateText = require('./libreTranslateWrapper');
const fs = require('fs-extra');
const projectConstants = require('./constants');
const { languagesToTranscribe, translationLanguages } = projectConstants;
let l = console.log;
if(global.debug === 'false'){
l = function(){}
}
function getCodeFromLanguageName(languageName){
return translationLanguages.find(function(filteredLanguage){
return languageName === filteredLanguage.name;
}).code
}
/** for translation **/
async function createTranslatedFiles({
directoryAndFileName,
language,
}){
const webVttData = await fs.readFile(`${directoryAndFileName}.vtt`, 'utf-8');
// copy original as copied
await fs.copy(`${directoryAndFileName}.vtt`, `${directoryAndFileName}_${language}.vtt`)
for(const languageToConvertTo of languagesToTranscribe){
l('languageToConvertTo');
l(languageToConvertTo);
l('language');
l(language);
try {
// no need to translate just copy the file
if(languageToConvertTo !== language){
// hit LibreTranslate backend
l(`hitting libretranslate: ${language} -> ${languageToConvertTo}`);
let translatedText = await translateText({
sourceLanguage: getCodeFromLanguageName(language), // before these were like 'EN', will full language work?
targetLanguage: getCodeFromLanguageName(languageToConvertTo),
text: webVttData,
})
// do the regexp here
translatedText.replace(/^(\d[\d:.]+\d) .*?( \d[\d:.]+\d)$/gm, "$1 -->$2");
translatedText = 'WEBVTT' + translatedText.slice(6);
await fs.writeFile(`${directoryAndFileName}_${languageToConvertTo}.vtt`, translatedText, 'utf-8');
}
} catch (err){
l(err);
l('error in translation');
return err
}
}
}
module.exports = createTranslatedFiles;