I'm trying to use DeepL API to translate some text files. When I make a request with a text file that has fewer than 3 words, the API response is correct and it gives me back the translated text file. However, when I try to do the same thing with a text file that has more than 3 words, the API doesn't translate anything and responds to the request with the text file untranslated.
I'm just started to learn about API, so anybody can help me with this?
const axios = require('axios');
const fs = require('fs');
// Replace [yourAuthKey] with your actual DeepL API authorization key
const deepLAuthKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
// User Inputs
const sourceLang = 'PT';
const targetLang = 'EN-US';
const inputFilePath = './root_text.txt';
const outputFilePath = './translated_text.txt';
// Function to read the text file
function readTextFile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
// Function to write the translated text to a file
function writeTextFile(filePath, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, data, 'utf8', (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
// Function to translate the text
async function translateText(text, sourceLang, targetLang) {
try {
// Prepare the request data
const requestData = {
text: encodeURIComponent(text),
source_lang: sourceLang,
target_lang: targetLang,
};
// Make a POST request to the DeepL API
const response = await axios.post(
'https://api-free.deepl.com/v2/translate',
requestData,
{
headers: {
Authorization: `DeepL-Auth-Key ${deepLAuthKey}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
// Extract the translated text from the API response
const translatedText = decodeURIComponent(response.data.translations[0].text);
return translatedText;
} catch (error) {
console.error('Translation error:', error);
throw error;
}
}
// Run the functions
readTextFile(inputFilePath)
.then(async (text) => {
// Call the translateText function
const translatedText = await translateText(text, sourceLang, targetLang);
console.log('Original Text:', text);
console.log('Translated Text:', translatedText);
return writeTextFile(outputFilePath, translatedText);
})
.then(() => {
console.log('Translated text saved to:', outputFilePath);
})
.catch((error) => {
console.error('Error:', error);
});