Translate keywords (#114)

This commit is contained in:
Niklas Fondberg
2022-07-01 11:54:51 +02:00
committed by GitHub
parent 35ad46cb6d
commit f8f91247cf
4 changed files with 90 additions and 13 deletions
+59
View File
@@ -0,0 +1,59 @@
const {
TranslateClient,
TranslateTextCommand,
} = require('@aws-sdk/client-translate');
const db = require('knex')({
client: 'pg',
connection: 'postgresql://fondberg:@docker.for.mac.localhost/photowall',
searchPath: ['public'],
});
async function translateText(input) {
const translateClient = new TranslateClient({
region: 'eu-west-1',
});
const translateTextCommand = new TranslateTextCommand({
SourceLanguageCode: input.sourceLanguageCode ?? 'auto',
TargetLanguageCode: input.targetLanguageCode,
Text: input.text,
});
return translateClient
.send(translateTextCommand)
.then((resp) => resp.TranslatedText);
}
function getLanguageCode(locale) {
let langCode = locale.value.substr(0, 2);
return langCode == 'nn' ? 'no' : langCode;
}
async function translate(locales, keyword) {
for (let i = 0; i < locales.length; i++) {
const langCode = getLanguageCode(locales[i]);
const input = {
text: keyword.value,
targetLanguageCode: langCode,
};
const translated = await translateText(input);
console.log(keyword.value + ' : ' + translated);
const res = await db('keywords_i18n')
.insert({
value: translated,
keyword_id: keyword.id,
locale_id: locales[i].id,
})
.returning('*');
}
}
async function main() {
const locales = await db.select().table('locales').whereNull('fallback_id');
const keywords = await db.select().table('keywords');
for (let i = 0; i < keywords.length; i++) {
await translate(locales, keywords[i]);
}
}
main();