46 lines
1.5 KiB
JavaScript
46 lines
1.5 KiB
JavaScript
const axios = require('axios');
|
|
const dotenv = require('dotenv');
|
|
|
|
dotenv.config();
|
|
|
|
const apiKey = process.env.GOOGLE_GEMINI_API_KEY;
|
|
|
|
/**
|
|
* Traduce un texto utilizando la API de Google Gemini.
|
|
* @param {String} text - Texto a traducir.
|
|
* @param {String} targetLang - Idioma de destino, 'es' para español.
|
|
* @returns {Promise<String>} - Texto traducido.
|
|
*/
|
|
const translateText = async (text, targetLang = 'es') => {
|
|
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${apiKey}`;
|
|
console.log('Texto crudo sin traduccion ' + text);
|
|
|
|
// Añadimos el preprompt para que especifique la traducción al español
|
|
const prompt = `Eres un experto en idiomas, tu tarea es traducir el siguiente texto al español:\n\n${text}`;
|
|
|
|
try {
|
|
const response = await axios.post(
|
|
url,
|
|
{
|
|
contents: [{ parts: [{ text: prompt }] }]
|
|
},
|
|
{
|
|
headers: { 'Content-Type': 'application/json' }
|
|
}
|
|
);
|
|
|
|
// Extrae el texto traducido de la respuesta
|
|
const translatedText = response.data.candidates[0].content.parts[0].text;
|
|
|
|
console.log('Texto traducido: ' + translatedText);
|
|
|
|
return translatedText;
|
|
} catch (error) {
|
|
console.error('Error al traducir el texto:', JSON.stringify(error.response?.data, null, 2));
|
|
return text; // Devuelve el texto original en caso de error
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
translateText
|
|
}; |