dealing with Deepl API

pol olory's icon

I am trying to create a text translator in max msp using Deepl API. The script made with node.script works, but I am not able to find a way to send a text to be translated to node.script. Does anyone have a method to accomplish this ?
Here is my patch

Max Patch
Copy patch and select New From Clipboard in Max.

here is de js code :
require('dotenv').config(); // Chargement des variables d'environnement depuis le fichier .env

const axios = require('axios');
const deepLApiKey = process.env.DEEPL_API_KEY;

const maxApi = require("max-api");

function translateText(text) {
const url = 'https://api.deepl.com/v2/translate';
const params = {
auth_key: deepLApiKey,
text: text,
target_lang: 'FR',
};

axios.post(url, null, { params })
.then(response => {
const translation = response.data.translations[0].text;
maxApi.outlet(translation); // Envoyer la traduction à Max MSP
})
.catch(error => {
console.error('Erreur lors de la traduction:', error);
});
}

maxApi.addHandler('message', (message) => {
const text = message.toString(); // Convertir le message en chaîne de caractères
translateText(text);
});

Thanks for your Answers !!! :-)

LSka's icon

check the "stdin-out" tab in the node.script helpfile for an example

pol olory's icon

Thanks ! I've been playing with [stdin-out] and it works quite good : my messages arrive in [node.script], but nothing comes out... not even a dictionary message... could there be any issue with my js code ? Here are the changes I've made in the patch:

Max Patch
Copy patch and select New From Clipboard in Max.

and here are the changes I've made in [node.script] :
require('dotenv').config(); //env variables

const axios = require('axios');
const deepLApiKey = process.env.DEEPL_API_KEY;
const readline = require('readline');

const Max = require("max-api");

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});

rl.on('line', function(line){

// This will be posted to the Max console
Max.post(`Received ${line} on stdin`);

// If you run this without Max, this will go to stdout, which is usually
// the JS console. In a node.script object, this output is redirected to Max
// with the prefix stdout
console.log(`Echoing ${line} to stdout`);
});

function translateText(text) {
const url = 'https://api.deepl.com/v2/translate';
const params = {
auth_key: deepLApiKey,
text: text,
target_lang: 'FR',
};

axios.post(url, null, { params })
.then(response => {
const translation = response.data.translations[0].text;
maxApi.outlet(translation); // Send translation to Max MSP
})
.catch(error => {
console.error('Erreur lors de la traduction:', error);
});
}
Max.addHandler('error', function() {
console.error("Error: Does not compute");
});

Max.addHandler('message', (message) => {
const text = message.toString(); // Convert the message in text string
translateText(text);
});

pol olory's icon

found better and easier translation solution with chat gpt :-)