Skip to content

Instantly share code, notes, and snippets.

@ddrigass
Created September 18, 2020 07:51
Show Gist options
  • Save ddrigass/2587f78b2cbce66e1abfa9c7384facc6 to your computer and use it in GitHub Desktop.
Save ddrigass/2587f78b2cbce66e1abfa9c7384facc6 to your computer and use it in GitHub Desktop.
Fill .mo and .xliff file from .xlsx spreadsheet
const PO = require('pofile');
const xlsx = require('node-xlsx');
const fs = require('fs');
const xlsxFile = xlsx.parse(`${__dirname}/languages2.xlsx`);
const websiteList = xlsxFile[0];
let notTranslated = [];
PO.load('smartfert-ru.po', function (err, po) {
po["items"].forEach((el, index) => {
let stringToTranslate = el["msgid"];
for (let row in websiteList["data"]) {
if (typeof el['msgid'] !== 'string' || (el["msgstr"] && el["msgstr"][0] !== "")) continue;
const engWord = websiteList["data"][row][4];
const rusWord = websiteList["data"][row][2];
if (clearString(engWord) === clearString(stringToTranslate)) {
el["msgstr"] = rusWord;
}
}
});
po.save('smartfert-ru-translated.po', function (err) {});
});
function clearString(str) {
if (!str || typeof str !== 'string') { return ''}
let modifyStr = str
.replace(/\r?\n/g, "")
.replace(/\s/g, '')
.replace(/<\/?[^>]+(>|$)/g, "")
.trim();
modifyStr = modifyStr.toLowerCase();
return modifyStr;
}
const xlsx = require('node-xlsx');
const fs = require('fs');
const xliff = require('xliff')
const xlsxFile = xlsx.parse(`${__dirname}/languages.xlsx`);
const websiteList = xlsxFile[0];
async function translateXliffFile(fileName) {
const data = fs.readFileSync(`./totranslate/${fileName}`, 'utf8');
xliff.xliff12ToJs(data, function (err, res) {
let translates = res["resources"][Object.keys(res["resources"])[0]];
let langrow = 0;
if (res['targetLanguage'] == 'fr') {
langrow = 6;
}
if (res['targetLanguage'] == 'pt-pt') {
langrow = 3;
}
if (res['targetLanguage'] == 'ru') {
langrow = 5;
}
if (res['targetLanguage'] == 'es') {
return;
}
for (let word in translates) {
const stringToTranslate = translates[word]["source"];
let translatedWord = translates[word]["target"];
for (let row in websiteList["data"]) {
const engWord = websiteList["data"][row][0];
const rusWord = websiteList["data"][row][langrow];
if (clearString(engWord) === clearString(stringToTranslate)) {
translates[word]["target"] = rusWord;
}
}
}
xliff.jsToXliff12(res, (err, resnew) => {
fs.writeFile(`./translated/${fileName}`, resnew, (err) => {
// In case of a error throw err.
if (err) throw err;
})
})
});
}
function clearString(str) {
if (!str || typeof str !== 'string') { return ''}
let modifyStr = str
.replace(/\r?\n/g, "")
.replace(/\s/g, '')
.replace(/<\/?[^>]+(>|$)/g, "")
.trim();
modifyStr = modifyStr.toLowerCase();
return modifyStr;
}
const files = fs.readdirSync('./totranslate/');
files.forEach(fileName => {
translateXliffFile(fileName)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment