Skip to content

Commit

Permalink
100% pronto
Browse files Browse the repository at this point in the history
  • Loading branch information
gabriel-logan committed Sep 16, 2023
1 parent fd4eec9 commit 5769847
Show file tree
Hide file tree
Showing 15 changed files with 4,531 additions and 1,060 deletions.
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ typescript/
package-lock.json
tsconfig.json
private/
jest.config.js
tests/
.npmignore
52 changes: 45 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,13 @@ Now, you can use the library to translate the JSON file into multiple languages:

```javascript
const { translateToMultipleFolders, translateToUnicFolder } = require('azure-translator-code');

// or

```
or
```javascript
import { translateToMultipleFolders, translateToUnicFolder } from 'azure-translator-code';
```

```javascript
const key = 'sds12312a213aaaa9b2d0c37eds37b'; // REPLACE WITH YOUR OWN KEY HERE
const endpoint = 'https://api.cognitive.microsofttranslator.com/';
const location = 'eastus';
Expand All @@ -80,25 +82,61 @@ const toLangs = [
'zh',
'pt-pt',
'ar',
'tlh-Latn',
'tlh-Latn'
];

const jsonFile = {
"translation": {
"welcome": "Welcome",
"hello": "Hello",
"hello": "Hello"
}
};

// Translation to multiple folders
translateToMultipleFolders(key, endpoint, location, fromLang, toLangs, jsonFile);
// This function will return a folder called folder multiFolderGeneratedTranslations
// This function will return a folder called multiFolderGeneratedTranslations



// Translation to a single folder
translateToUnicFolder(key, endpoint, location, fromLang, toLangs, jsonFile);
// This function will return a folder called folder unicFolderGeneratedTranslations
// This function will return a folder called unicFolderGeneratedTranslations
```

#### You can also choose the folder or folder name where you will save the files.
##### Saving always starts from the project root folder.

```javascript
const { translateToMultipleFolders, translateToUnicFolder } = require('azure-translator-code');

const key = 'sds12312a213aaaa9b2d0c37eds37b'; // REPLACE WITH YOUR OWN KEY HERE
const endpoint = 'https://api.cognitive.microsofttranslator.com/';
const location = 'eastus';
const fromLang = 'en';
const toLangs = ['pt', 'de'];

const jsonFile = {
"translation": {
"welcome": "Welcome",
"hello": "Hello",
}
};

// IMPORTANT: If you use '../../' it will try to save to a location before the root folder

// Translation to multiple folders
translateToMultipleFolders(key, endpoint, location, fromLang, toLangs, jsonFile, 'myFolder');
// This function will return a folder called myFolder


// Translation to a single folder
translateToUnicFolder(key, endpoint, location, fromLang, toLangs, jsonFile, 'myFolder/OtherFolder/etc');
// This function will return a folder called ./myFolder/OtherFolder/etc


// Translation to a single folder
translateToUnicFolder(key, endpoint, location, fromLang, toLangs, jsonFile, './myFolder/OtherFolder/etc');
// This function will return a folder called ./myFolder/OtherFolder/etc
```

Make sure to replace the key and endpoint information with your own Azure access credentials. Ensure that the JSON file and settings are correctly defined according to your needs.
Expand Down
4 changes: 2 additions & 2 deletions javascript/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.translateToUnicFolder = exports.translateToMultipleFolders = void 0;
const translateToMultipleFolders_1 = __importDefault(require("./translateToMultipleFolders"));
var translateToMultipleFolders_1 = __importDefault(require("./translateToMultipleFolders"));
exports.translateToMultipleFolders = translateToMultipleFolders_1.default;
const translateToUnicFolder_1 = __importDefault(require("./translateToUnicFolder"));
var translateToUnicFolder_1 = __importDefault(require("./translateToUnicFolder"));
exports.translateToUnicFolder = translateToUnicFolder_1.default;
150 changes: 112 additions & 38 deletions javascript/translateToMultipleFolders/index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,55 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const uuid_1 = require("uuid");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
function translateToMultipleFolders(key, endpoint, location, fromLang, toLangs, jsonFile) {
const folderName = 'multiFolderGeneratedTranslations';
const traducoesDir = path_1.default.join(__dirname, '..', '..', '..', '..', folderName);
var axios_1 = __importDefault(require("axios"));
var uuid_1 = require("uuid");
var fs_1 = __importDefault(require("fs"));
var path_1 = __importDefault(require("path"));
function translateToMultipleFolders(key, endpoint, location, fromLang, toLangs, jsonFile, folderNamePath) {
if (folderNamePath === void 0) { folderNamePath = 'multiFolderGeneratedTranslations'; }
var traducoesDir = path_1.default.join(__dirname, '..', '..', '..', '..', folderNamePath);
if (!fs_1.default.existsSync(traducoesDir)) {
fs_1.default.mkdirSync(traducoesDir);
fs_1.default.mkdirSync(traducoesDir, { recursive: true });
}
const { translation } = jsonFile;
var translation = jsonFile.translation;
function translateText(text, from, to) {
return (0, axios_1.default)({
baseURL: endpoint,
Expand All @@ -38,38 +74,76 @@ function translateToMultipleFolders(key, endpoint, location, fromLang, toLangs,
responseType: 'json',
});
}
async function translateAndSave(lang) {
const translations = {};
for (const key in translation) {
try {
const response = await translateText(translation[key], fromLang, lang);
const translatedText = response.data[0].translations[0].text;
translations[key] = translatedText;
console.log(`Traduzindo ${translation[key]} para ${lang} \n\n`);
}
catch (error) {
if (error instanceof Error) {
console.error(`Erro ao traduzir "${key}" para ${lang}: ${error.message} \n`);
function translateAndSave(lang) {
return __awaiter(this, void 0, void 0, function () {
var translations, _a, _b, _c, _i, key_1, response, translatedText, error_1, langDir, outputFileName;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
translations = {};
_a = translation;
_b = [];
for (_c in _a)
_b.push(_c);
_i = 0;
_d.label = 1;
case 1:
if (!(_i < _b.length)) return [3, 6];
_c = _b[_i];
if (!(_c in _a)) return [3, 5];
key_1 = _c;
_d.label = 2;
case 2:
_d.trys.push([2, 4, , 5]);
return [4, translateText(translation[key_1], fromLang, lang)];
case 3:
response = _d.sent();
translatedText = response.data[0].translations[0].text;
translations[key_1] = translatedText;
console.log("Translating ".concat(translation[key_1], " to ").concat(lang, " \n\n"));
return [3, 5];
case 4:
error_1 = _d.sent();
if (error_1 instanceof Error) {
console.error("Error translating \"".concat(key_1, "\" to ").concat(lang, ": ").concat(error_1.message, " \n"));
}
else {
console.error("An error occurred within the error (: \n");
}
return [3, 5];
case 5:
_i++;
return [3, 1];
case 6:
langDir = path_1.default.join(traducoesDir, lang);
if (!fs_1.default.existsSync(langDir)) {
fs_1.default.mkdirSync(langDir);
}
outputFileName = path_1.default.join(langDir, "".concat(lang, ".json"));
fs_1.default.writeFileSync(outputFileName, JSON.stringify({ translation: translations }, null, 4));
console.log("Translations for ".concat(lang, " saved in ").concat(outputFileName, " \n\n"));
return [2];
}
else {
console.error(`Algum erro aconteceu no erro (: \n`);
}
}
}
const langDir = path_1.default.join(traducoesDir, lang);
if (!fs_1.default.existsSync(langDir)) {
fs_1.default.mkdirSync(langDir);
}
const outputFileName = path_1.default.join(langDir, `${lang}.json`);
fs_1.default.writeFileSync(outputFileName, JSON.stringify({ translation: translations }, null, 4));
console.log(`Traduções para ${lang} salvas em ${outputFileName} \n\n`);
});
});
}
async function translateAndSaveAll() {
const translationPromises = toLangs.map((lang) => translateAndSave(lang));
await Promise.all(translationPromises);
function translateAndSaveAll() {
return __awaiter(this, void 0, void 0, function () {
var translationPromises;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
translationPromises = toLangs.map(function (lang) { return translateAndSave(lang); });
return [4, Promise.all(translationPromises)];
case 1:
_a.sent();
return [2];
}
});
});
}
translateAndSaveAll().catch((error) => {
console.error(`Erro ao traduzir e salvar textos: ${error.message} \n`);
translateAndSaveAll().catch(function (error) {
console.error("Error translating and saving texts: ".concat(error.message, " \n"));
});
}
exports.default = translateToMultipleFolders;
Loading

0 comments on commit 5769847

Please sign in to comment.