Last active
January 2, 2024 14:53
-
-
Save dadodasyra/50435d11891116dfaa7ecd06781722b3 to your computer and use it in GitHub Desktop.
This little scripts translate from an ini file to another one using google translate api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import translate from "translate"; | |
translate.engine = "google"; // Or "yandex", "libre", "deepl" | |
translate.key = ""; | |
const langSource = "fr"; | |
const langDest = "tr"; | |
//Read langSource.ini line by line | |
import fs from "fs"; | |
import { promisify } from "util"; | |
const readFile = promisify(fs.readFile); | |
const writeFile = promisify(fs.writeFile); | |
let file = await readFile(langSource+'.ini', 'utf8'); | |
let lines = file.split("\r"); | |
//Translate each line | |
let translated = []; | |
let error = 0; | |
for(let i = 0; i < lines.length; i++) { | |
let line = lines[i]; | |
let split = line.split("="); | |
if (!split[1]) { | |
translated.push(line); | |
continue; | |
} | |
let key = split[0]; | |
let value = split[1]; | |
//replace \{([A-z])\w+\} with {0} {1} etc | |
let matches = value.match(/\{([A-z])\w+}/g); | |
if (matches) { | |
for (let i = 0; i < matches.length; i++) { | |
value = value.replace(matches[i], "{" + i + "}"); | |
} | |
} | |
//replace \%([A-z])\w+\% with %0% %1% etc | |
let matches2 = value.match(/%([A-z])\w+%/g); | |
if (matches2) { | |
for (let i = 0; i < matches2.length; i++) { | |
value = value.replace(matches2[i], "%" + i + "%"); | |
} | |
} | |
console.log(matches, matches2) | |
console.log(value) | |
let translatedValue = value; | |
try{ | |
translatedValue = await translate(value, {from: langSource, to: langDest}); | |
} catch(Error) { | |
error++; | |
console.log(Error) | |
translatedValue = value; | |
} finally { | |
//get back {0} {1} etc | |
if (matches) { | |
for (let i = 0; i < matches.length; i++) { | |
translatedValue = translatedValue.replace("{" + i + "}", matches[i]); | |
} | |
} | |
//get back %0% %1% etc | |
if (matches2) { | |
for (let i = 0; i < matches2.length; i++) { | |
translatedValue = translatedValue.replace("%" + i + "%", matches2[i]); | |
} | |
} | |
translated.push(key+"="+translatedValue); | |
} | |
} | |
//push result into new file | |
await writeFile(langDest+'.ini', translated.join("\r")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment