From 65fa7a38d356be361feeddf492313f2bef5f024d Mon Sep 17 00:00:00 2001 From: gabriel-logan Date: Sat, 1 Jun 2024 22:30:58 -0300 Subject: [PATCH] update to work with generic jsons --- package.json | 2 +- src/addInto/index.ts | 125 ---------------------- src/index.ts | 3 +- src/translate/index.ts | 80 ++++++++++++++ src/translateToMultipleFolders/index.ts | 55 ++++++---- src/translateToUnicFolder/index.ts | 67 ++++++------ src/updateTranslationUnic/index.ts | 133 ------------------------ 7 files changed, 147 insertions(+), 318 deletions(-) delete mode 100644 src/addInto/index.ts create mode 100644 src/translate/index.ts delete mode 100644 src/updateTranslationUnic/index.ts diff --git a/package.json b/package.json index bd8c2f6..15fcdda 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "azure-translator-code", - "version": "1.1.0", + "version": "1.1.1", "description": "Azure Cognitive Services Translator Text API Code for Use with Common Languages", "author": { "name": "Gabriel Logan" diff --git a/src/addInto/index.ts b/src/addInto/index.ts deleted file mode 100644 index 9458b0d..0000000 --- a/src/addInto/index.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** - * import axios from 'axios'; -import { v4 as uuidv4 } from 'uuid'; -import fs from 'fs'; -import path from 'path'; - -interface TranslationType { - translation: Record; -} - -export default function addInto( - key: string, - endpoint: string, - location: string, - fromLang: string, - toLangs: string[], - jsonFile: TranslationType, - folderName: string = 'unicFolderGeneratedTranslations', -) { - const traducoesDir: string = path.join(__dirname, '..', '..', folderName); - - if (!fs.existsSync(traducoesDir)) { - fs.mkdirSync(traducoesDir, { recursive: true }); - } - - const { translation } = jsonFile; - - function translateText(text: string, from: string, to: string) { - return axios({ - baseURL: endpoint, - url: '/translate', - method: 'post', - headers: { - 'Ocp-Apim-Subscription-Key': key, - 'Ocp-Apim-Subscription-Region': location, - 'Content-type': 'application/json', - 'X-ClientTraceId': uuidv4().toString(), - }, - params: { - 'api-version': '3.0', - from: from, - to: to, - }, - data: [ - { - text: text, - }, - ], - responseType: 'json', - }); - } - - async function translateAndSave(lang: string, existingTranslations: Record = {}) { - const translations: Record = {}; - - for (const key in translation) { - try { - console.log('TO FAZENDO UMA REQUISICAO'); - const response = await translateText(translation[key], fromLang, lang); - const translatedText: string = response.data[0].translations[0].text; - translations[key] = translatedText; - console.log(`Translating ${translation[key]} to ${lang} \n\n`); - } catch (error) { - if (error instanceof Error) { - console.error(`Error translating "${key}" to ${lang}: ${error.message} \n`); - } else { - console.error(`An error occurred within the error (: \n`); - } - } - } - - const mergedTranslations = { ...existingTranslations, ...translations }; - return mergedTranslations; - } - - async function translateAndSaveAll() { - let existingTranslations: Record = {}; - - // Load existing translations if the files exist - for (const lang of toLangs) { - const filePath = path.join(traducoesDir, `${lang}.json`); - if (fs.existsSync(filePath)) { - const fileContent = fs.readFileSync(filePath, 'utf-8'); - const jsonData = JSON.parse(fileContent); - existingTranslations = { ...existingTranslations, ...jsonData.translation }; - } - } - - const translationPromises = toLangs.map((lang) => translateAndSave(lang, existingTranslations)); - - const mergedTranslations = await Promise.all(translationPromises); - - for (const [index, lang] of toLangs.entries()) { - const outputFileName = path.join(traducoesDir, `${lang}.json`); - fs.writeFileSync( - outputFileName, - JSON.stringify({ translation: mergedTranslations[index] }, null, 4), - ); - console.log(`Translations for ${lang} saved in ${outputFileName} \n\n`); - } - } - - translateAndSaveAll().catch((error) => { - console.error(`Error translating and saving texts: ${error.message} \n`); - }); -} - -const jsonFile = { - translation: { - AAAaddwd: 'AWdD', - AAAdaasdwd: '123456', - AAasdAawd: 'AWasdD', - AAasdAaawd: 'AasdWD', - AAAasasadwd: 'AasdWD', - }, -}; -const key = '50ee9953ce4b4c0cab5e00f08518fe9f'; // THIS CODE NOT WORK, REPLACE YOURS HERE -const endpoint = 'https://api.cognitive.microsofttranslator.com/'; -const location = 'eastus2'; -const fromLang = 'en'; -const toLangs = ['pt', 'es', 'de']; - -addInto(key, endpoint, location, fromLang, toLangs, jsonFile); - - */ diff --git a/src/index.ts b/src/index.ts index 76965bb..1612917 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ import translateToMultipleFolders from './translateToMultipleFolders'; import translateToUnicFolder from './translateToUnicFolder'; import updateTranslationsMulti from './updateTranslationMulti'; +import translate from './translate'; -export { translateToMultipleFolders, translateToUnicFolder, updateTranslationsMulti }; +export { translateToMultipleFolders, translateToUnicFolder, updateTranslationsMulti, translate }; diff --git a/src/translate/index.ts b/src/translate/index.ts new file mode 100644 index 0000000..057fb2f --- /dev/null +++ b/src/translate/index.ts @@ -0,0 +1,80 @@ +import axios from 'axios'; +import { v4 as uuidv4 } from 'uuid'; + +/** + * Represents the type of a translation object. + */ +type TranslationType = { + [key: string]: string | TranslationType; +}; + +async function translateText( + text: string, + from: string, + to: string, + endpoint: string, + key: string, + location: string, +) { + return axios({ + baseURL: endpoint, + url: '/translate', + method: 'post', + headers: { + 'Ocp-Apim-Subscription-Key': key, + 'Ocp-Apim-Subscription-Region': location, + 'Content-type': 'application/json', + 'X-ClientTraceId': uuidv4().toString(), + }, + params: { + 'api-version': '3.0', + from: from, + to: to, + }, + data: [ + { + text: text, + }, + ], + responseType: 'json', + }); +} + +/** + * Translates a JSON object from one language to another using the Azure Translator service. + * @param key - The Azure Translator subscription key. + * @param endpoint - The Azure Translator endpoint URL. + * @param location - The Azure Translator subscription region. + * @param fromLang - The language code of the source language. + * @param toLang - The language code of the target language. + * @param jsonFile - The JSON object to be translated. + * @returns A Promise that resolves to the translated JSON object. + */ +export default async function translate( + key: string, + endpoint: string, + location: string, + fromLang: string, + toLang: string, + jsonFile: TranslationType, +): Promise { + const translatedJson: TranslationType = {}; + + for (const [jsonKey, jsonValue] of Object.entries(jsonFile)) { + if (typeof jsonValue === 'string') { + const response = await translateText(jsonValue, fromLang, toLang, endpoint, key, location); + translatedJson[jsonKey] = response.data[0].translations[0].text; + } else { + translatedJson[jsonKey] = await translate( + key, + endpoint, + location, + fromLang, + toLang, + jsonValue, + ); + } + } + + return translatedJson; +} diff --git a/src/translateToMultipleFolders/index.ts b/src/translateToMultipleFolders/index.ts index 3e705c0..1455546 100644 --- a/src/translateToMultipleFolders/index.ts +++ b/src/translateToMultipleFolders/index.ts @@ -1,11 +1,11 @@ import axios from 'axios'; import { v4 as uuidv4 } from 'uuid'; -import fs from 'fs'; -import path from 'path'; +import * as fs from 'fs'; +import * as path from 'path'; -interface TranslationType { - translation: Record; -} +type TranslationType = { + [key: string]: string | TranslationType; +}; /** * @param key Your key from azure translator, something like: 'sds12312a213aaaa9b2d0c37eds37b' @@ -67,8 +67,6 @@ export default function translateToMultipleFolders( fs.mkdirSync(traducoesDir, { recursive: true }); // Use { recursive: true } para criar pastas recursivamente, se necessário } - const { translation } = jsonFile; - function translateText(text: string, from: string, to: string) { return axios({ baseURL: endpoint, @@ -94,20 +92,31 @@ export default function translateToMultipleFolders( }); } - async function translateAndSave(lang: string) { - const translations: Record = {}; + async function translateAndSave(lang: string, obj: TranslationType, currentPath: string = '') { + const translations: Record = {}; - 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(`Translating ${translation[key]} to ${lang} \n\n`); - } catch (error) { - if (error instanceof Error) { - console.error(`Error translating "${key}" to ${lang}: ${error.message} \n`); - } else { - console.error(`An error occurred within the error (: \n`); + for (const key in obj) { + const newPath = currentPath ? `${currentPath}.${key}` : key; + + if (typeof obj[key] === 'object' && obj[key] !== null) { + const nestedTranslations = await translateAndSave( + lang, + obj[key] as TranslationType, + newPath, + ); + translations[key] = nestedTranslations; + } else { + try { + const response = await translateText(obj[key] as string, fromLang, lang); + const translatedText = response.data[0].translations[0].text; + translations[key] = translatedText; + console.log(`Translating ${obj[key]} to ${lang} \n\n`); + } catch (error) { + if (error instanceof Error) { + console.error(`Error translating "${newPath}" to ${lang}: ${error.message} \n`); + } else { + console.error(`An error occurred within the error (: \n`); + } } } } @@ -119,12 +128,14 @@ export default function translateToMultipleFolders( } const outputFileName = path.join(langDir, `${lang}.json`); - fs.writeFileSync(outputFileName, JSON.stringify({ translation: translations }, null, 4)); + fs.writeFileSync(outputFileName, JSON.stringify(translations, null, 4)); console.log(`Translations for ${lang} saved in ${outputFileName} \n\n`); + + return translations; } async function translateAndSaveAll() { - const translationPromises = toLangs.map((lang) => translateAndSave(lang)); + const translationPromises = toLangs.map((lang) => translateAndSave(lang, jsonFile)); await Promise.all(translationPromises); } diff --git a/src/translateToUnicFolder/index.ts b/src/translateToUnicFolder/index.ts index 4b0d6a3..cfbf507 100644 --- a/src/translateToUnicFolder/index.ts +++ b/src/translateToUnicFolder/index.ts @@ -1,12 +1,11 @@ import axios from 'axios'; import { v4 as uuidv4 } from 'uuid'; -import fs from 'fs'; -import path from 'path'; - -interface TranslationType { - translation: Record; -} +import * as fs from 'fs'; +import * as path from 'path'; +type TranslationType = { + [key: string]: string | TranslationType; +}; /** * @param key Your key from azure translator, something like: 'sds12312a213aaaa9b2d0c37eds37b' * @param endpoint The endpoint: 'https://api.cognitive.microsofttranslator.com/' @@ -59,16 +58,14 @@ export default function translateToUnicFolder( fromLang: string, toLangs: string[], jsonFile: TranslationType, - folderName: string = 'unicFolderGeneratedTranslations', // Onde sera salvo os arquivos + folderNamePath: string = 'unicFolderGeneratedTranslations', // Onde sera salvo os arquivos ): void { - const traducoesDir: string = path.join(__dirname, '..', '..', '..', '..', folderName); + const traducoesDir: string = path.join(__dirname, '..', '..', '..', '..', folderNamePath); if (!fs.existsSync(traducoesDir)) { fs.mkdirSync(traducoesDir, { recursive: true }); // Use { recursive: true } para criar pastas recursivamente, se necessário } - const { translation } = jsonFile; - function translateText(text: string, from: string, to: string) { return axios({ baseURL: endpoint, @@ -94,42 +91,40 @@ export default function translateToUnicFolder( }); } - const outputData: Record = {}; - - async function translateAndSave(lang: string) { - const translations: Record = {}; + async function translateAndSave(lang: string, obj: TranslationType) { + const translations: Record = {}; - for (const key in translation) { - try { - const response = await translateText(translation[key], fromLang, lang); - const translatedText: string = response.data[0].translations[0].text; - translations[key] = translatedText; - console.log(`Translating ${translation[key]} to ${lang} \n\n`); - } catch (error) { - if (error instanceof Error) { - console.error(`Error translating "${key}" to ${lang}: ${error.message} \n`); - } else { - console.error(`An error occurred within the error (: \n`); + for (const key in obj) { + if (typeof obj[key] === 'object' && obj[key] !== null) { + const nestedTranslations = await translateAndSave(lang, obj[key] as TranslationType); + translations[key] = nestedTranslations; + } else { + try { + const response = await translateText(obj[key] as string, fromLang, lang); + const translatedText = response.data[0].translations[0].text; + translations[key] = translatedText; + console.log(`Translating ${obj[key]} to ${lang} \n\n`); + } catch (error) { + if (error instanceof Error) { + console.error(`Error translating "${key}" to ${lang}: ${error.message} \n`); + } else { + console.error(`An error occurred within the error (: \n`); + } } } } - outputData[lang] = translations; + const outputFileName = path.join(traducoesDir, `${lang}.json`); + fs.writeFileSync(outputFileName, JSON.stringify(translations, null, 4)); + console.log(`Translations for ${lang} saved in ${outputFileName} \n\n`); + + return translations; } async function translateAndSaveAll() { - const translationPromises = toLangs.map((lang) => translateAndSave(lang)); + const translationPromises = toLangs.map((lang) => translateAndSave(lang, jsonFile)); await Promise.all(translationPromises); - - for (const lang of toLangs) { - const outputFileName = path.join(traducoesDir, `${lang}.json`); - fs.writeFileSync( - outputFileName, - JSON.stringify({ translation: outputData[lang] as TranslationType }, null, 4), - ); - console.log(`Translations for ${lang} saved in ${outputFileName} \n\n`); - } } translateAndSaveAll().catch((error) => { diff --git a/src/updateTranslationUnic/index.ts b/src/updateTranslationUnic/index.ts deleted file mode 100644 index 741cd53..0000000 --- a/src/updateTranslationUnic/index.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * import axios from 'axios'; -import { v4 as uuidv4 } from 'uuid'; -import fs from 'fs'; -import path from 'path'; - -interface TranslationType { - translation: Record; -} - -export default function updateTranslations( - key: string, - endpoint: string, - location: string, - fromLang: string, - toLangs: string[], - jsonFile: TranslationType, - folderName: string = 'unicFolderGeneratedTranslations', -) { - const traducoesDir: string = path.join(__dirname, '..', '..', folderName); - - if (!fs.existsSync(traducoesDir)) { - fs.mkdirSync(traducoesDir, { recursive: true }); - } - - const { translation } = jsonFile; - - function translateText(text: string, from: string, to: string) { - return axios({ - baseURL: endpoint, - url: '/translate', - method: 'post', - headers: { - 'Ocp-Apim-Subscription-Key': key, - 'Ocp-Apim-Subscription-Region': location, - 'Content-type': 'application/json', - 'X-ClientTraceId': uuidv4().toString(), - }, - params: { - 'api-version': '3.0', - from: from, - to: to, - }, - data: [ - { - text: text, - }, - ], - responseType: 'json', - }); - } - - async function translateAndSave(lang: string, existingTranslations: Record = {}) { - const translations: Record = {}; - - for (const key in translation) { - // Verifique se a tradução já existe no idioma de destino - if (!existingTranslations[key]) { - try { - console.log('TO FAZENDO UMA REQUISICAO'); - const response = await translateText(translation[key], fromLang, lang); - const translatedText: string = response.data[0].translations[0].text; - translations[key] = translatedText; - console.log(`Translating ${translation[key]} to ${lang} \n\n`); - } catch (error) { - if (error instanceof Error) { - console.error(`Error translating "${key}" to ${lang}: ${error.message} \n`); - } else { - console.error(`An error occurred within the error (: \n`); - } - } - } else { - // A tradução já existe, use a tradução existente - translations[key] = existingTranslations[key]; - } - } - - const mergedTranslations = { ...existingTranslations, ...translations }; - return mergedTranslations; - } - - async function translateAndSaveAll() { - let existingTranslations: Record = {}; - - // Load existing translations if the files exist - for (const lang of toLangs) { - const filePath = path.join(traducoesDir, `${lang}.json`); - if (fs.existsSync(filePath)) { - const fileContent = fs.readFileSync(filePath, 'utf-8'); - const jsonData = JSON.parse(fileContent); - existingTranslations = { ...existingTranslations, ...jsonData.translation }; - } - } - - const translationPromises = toLangs.map((lang) => translateAndSave(lang, existingTranslations)); - - const mergedTranslations = await Promise.all(translationPromises); - - for (const [index, lang] of toLangs.entries()) { - const outputFileName = path.join(traducoesDir, `${lang}.json`); - fs.writeFileSync( - outputFileName, - JSON.stringify({ translation: mergedTranslations[index] }, null, 4), - ); - console.log(`Translations for ${lang} saved in ${outputFileName} \n\n`); - } - } - - translateAndSaveAll().catch((error) => { - console.error(`Error translating and saving texts: ${error.message} \n`); - }); -} - -const jsonFile = { - translation: { - AAAaddwd: 'AWdD', - AAAdaad: 'AWjkldD', - AAasdAawd: 'Hi friend', - AAasdasd: 'AasdWD', - AAAasasadwd: 'AasdWD', - 'EAI GAY': 'HELLO GAY', - haha: 'Hi bro', - }, -}; -const key = '50ee9953ce4b4c0cab5e00f08518fe9f'; // THIS CODE NOT WORK, REPLACE YOURS HERE -const endpoint = 'https://api.cognitive.microsofttranslator.com/'; -const location = 'eastus2'; -const fromLang = 'en'; -const toLangs = ['pt', 'es', 'de']; - -updateTranslations(key, endpoint, location, fromLang, toLangs, jsonFile); - - */