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} - Texto traducido. */ const translateText = async (text, targetLang = 'es') => { const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${apiKey}`; // Añadimos el preprompt para que especifique la traducción al español const prompt = `Por favor, traduce 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; 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 };