3361 lines
111 KiB
JavaScript
3361 lines
111 KiB
JavaScript
require('../connections/mysql-server');
|
|
require('../helpers/CheckToken');
|
|
const formidable = require('formidable');
|
|
const express = require('express');
|
|
const router = express.Router();
|
|
const crypto = require('crypto');
|
|
//const { uploadFileToBucket, getFileStream, deleteFileStream } = require('../s3');
|
|
var { spawn } = require('child_process');
|
|
let bodyParser = require('body-parser');
|
|
router.use(
|
|
bodyParser.json({
|
|
verify: function getRawBody(req, res, buf) {
|
|
req.rawBody = buf.toString();
|
|
},
|
|
})
|
|
);
|
|
|
|
//Payed
|
|
const watsonIMBKey = 'ihcWQ89rxCAKDQgyXh7wU4bI_9R2zxjBmcevXA1_x3t1';
|
|
const watsonURLService =
|
|
'https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/96918c09-fa7d-495f-9413-646e624e46b6';
|
|
|
|
//Free
|
|
//const watsonIMBKey = "EJtHH83IMSkHk64oDmrVbwwk_RPnrOu0vgbWJ-O7k5kR";
|
|
//const watsonURLService = "https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/aa14db78-af38-45ae-9c94-1f226ef325c1";
|
|
|
|
const STTWatsonKey = 'psg1n6enCs0R5MHuEOkCKoCUKOeLFSgBk00eDl0s8T9n';
|
|
const STTWatsonService =
|
|
'https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/6cdb8798-77e4-4e5d-bcc9-b03ce151ee55';
|
|
|
|
var routes = function () {
|
|
//#region CHATTIME
|
|
router.get('/getAllChattime', verifyJWT, (req, res) => {
|
|
execSQLQuery(
|
|
`SELECT
|
|
*
|
|
from zoechattime;`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
});
|
|
|
|
router.get('/getChattime/:idzoechattime', verifyJWT, (req, res) => {
|
|
const idzoechattime = parseInt(req.params.idzoechattime);
|
|
execSQLQuery(
|
|
`SELECT
|
|
*
|
|
from zoechattime
|
|
where idzoechattime = ${idzoechattime};`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
});
|
|
|
|
router.post('/insertChattime', verifyJWT, (req, res) => {
|
|
const idzoechattime = parseInt(req.body.idzoechattime);
|
|
const description = req.body.description;
|
|
execSQLQuery(
|
|
`INSERT INTO zoechattime (description)
|
|
VALUES (?);`,
|
|
res,
|
|
req.originalUrl,
|
|
[description]
|
|
);
|
|
});
|
|
|
|
router.patch('/updateChattime', verifyJWT, (req, res) => {
|
|
const idzoechattime = parseInt(req.body.idzoechattime);
|
|
const description = req.body.description;
|
|
execSQLQuery(
|
|
`UPDATE zoechattime SET
|
|
description = ?
|
|
WHERE idzoechattime = ?;`,
|
|
res,
|
|
req.originalUrl,
|
|
[description, idzoechattime]
|
|
);
|
|
});
|
|
|
|
router.delete('/deleteChattime/:idzoechattime', verifyJWT, (req, res) => {
|
|
const idzoechattime = parseInt(req.params.idzoechattime);
|
|
execSQLQuery(
|
|
`delete from zoechattime
|
|
where idzoechattime = ${idzoechattime};`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
});
|
|
|
|
//#endregion
|
|
|
|
//#region CHATTIME DIALOG
|
|
router.get('/getChattimedialog/:idzoechattime', verifyJWT, (req, res) => {
|
|
const idzoechattime = parseInt(req.params.idzoechattime);
|
|
execSQLQuery(
|
|
`SELECT
|
|
*
|
|
from zoechattimedialog
|
|
where idzoechattime = ${idzoechattime};`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
});
|
|
|
|
router.post('/insertChattimedialog', verifyJWT, (req, res) => {
|
|
const idzoechattimedialog = parseInt(req.body.idzoechattimedialog);
|
|
const idzoechattime = parseInt(req.body.idzoechattime);
|
|
const zoetalking = req.body.zoetalking;
|
|
const speed = req.body.speed;
|
|
const phrase = req.body.phrase;
|
|
const ordem = parseInt(req.body.ordem);
|
|
const percent = parseInt(req.body.percent);
|
|
const english = req.body.english ? 1 : 0;
|
|
const sub = parseInt(req.body.sub);
|
|
const seq = parseInt(req.body.seq);
|
|
const seq_dir = parseInt(req.body.seq_dir);
|
|
const explanation = req.body.explanation;
|
|
const ex_english = req.body.ex_english ? 1 : 0;
|
|
const img = req.body.img;
|
|
const idzoevoices = req.body.idzoevoices;
|
|
const idzoevoices_ex = req.body.idzoevoices_ex;
|
|
execSQLQuery(
|
|
`INSERT INTO zoechattimedialog (idzoechattime, zoetalking, speed, phrase, ordem, percent, english, sub, seq, seq_dir, explanation, ex_english, img, idzoevoices, idzoevoices_ex)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
|
|
res,
|
|
req.originalUrl,
|
|
[
|
|
idzoechattime,
|
|
zoetalking,
|
|
speed,
|
|
phrase,
|
|
ordem,
|
|
percent,
|
|
english,
|
|
sub,
|
|
seq,
|
|
seq_dir,
|
|
explanation,
|
|
ex_english,
|
|
img,
|
|
idzoevoices,
|
|
idzoevoices_ex,
|
|
]
|
|
);
|
|
});
|
|
router.delete(
|
|
'/deleteChattimedialog/:idzoechattime',
|
|
verifyJWT,
|
|
(req, res) => {
|
|
const idzoechattime = parseInt(req.params.idzoechattime);
|
|
execSQLQuery(
|
|
`delete from zoechattimedialog
|
|
where idzoechattime = ${idzoechattime};`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
}
|
|
);
|
|
|
|
router.get('/getZoeVoices', verifyJWT, (req, res) => {
|
|
execSQLQuery(
|
|
`SELECT
|
|
*
|
|
from zoevoices
|
|
where disabled = 0;`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
});
|
|
|
|
//#endregion
|
|
|
|
//#region CHATTIME SENTENCES
|
|
router.get(
|
|
'/getChattimesentences/:idzoechattimedialog',
|
|
verifyJWT,
|
|
(req, res) => {
|
|
const idzoechattimedialog = parseInt(req.params.idzoechattimedialog);
|
|
execSQLQuery(
|
|
`SELECT
|
|
*
|
|
from zoechattimesentences
|
|
where idzoechattimedialog = ${idzoechattimedialog};`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
}
|
|
);
|
|
|
|
router.post('/insertChattimesentences', verifyJWT, (req, res) => {
|
|
const idzoechattimesentences = parseInt(req.body.idzoechattimesentences);
|
|
const idzoechattimedialog = parseInt(req.body.idzoechattimedialog);
|
|
const sentence = req.body.sentence;
|
|
const seq_dir = parseInt(req.body.seq_dir);
|
|
const ordem_dir = parseInt(req.body.ordem_dir);
|
|
const ex_answer = req.body.ex_answer ? 1 : 0;
|
|
execSQLQuery(
|
|
`INSERT INTO zoechattimesentences (idzoechattimedialog, sentence, seq_dir, ordem_dir, ex_answer)
|
|
VALUES (?, ?, ?, ?, ?);`,
|
|
res,
|
|
req.originalUrl,
|
|
[idzoechattimedialog, sentence, seq_dir, ordem_dir, ex_answer]
|
|
);
|
|
});
|
|
|
|
router.delete(
|
|
'/deleteChattimesentences/:idzoechattime',
|
|
verifyJWT,
|
|
(req, res) => {
|
|
const idzoechattime = parseInt(req.params.idzoechattime);
|
|
execSQLQuery(
|
|
`delete from zoechattimesentences
|
|
where idzoechattimedialog in (select idzoechattimedialog from zoechattimedialog where idzoechattime = ${idzoechattime});`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
}
|
|
);
|
|
|
|
//#endregion
|
|
|
|
//#region TRATAMENTO CHAT BOT
|
|
|
|
router.get('/getAllTratamentoChatBot', verifyJWT, (req, res) => {
|
|
execSQLQuery(
|
|
`SELECT
|
|
tf.*,
|
|
cb.description as 'NameChatBot'
|
|
from zoetratamentofrases tf
|
|
inner join ChatBot cb on cb.ChatBot = tf.ChatBot;`,
|
|
res,
|
|
req.originalUrl
|
|
);
|
|
});
|
|
|
|
router.post('/insertTratamentoChatBot', verifyJWT, (req, res) => {
|
|
const ChatBot = parseInt(req.body.ChatBot);
|
|
const frase = req.body.frase;
|
|
const trocada = req.body.trocada;
|
|
const habilitado = req.body.habilitado ? 1 : 0;
|
|
execSQLQuery(
|
|
`INSERT INTO zoetratamentofrases (ChatBot, frase, trocada, habilitado)
|
|
VALUES (?, ?, ?, ?);`,
|
|
res,
|
|
req.originalUrl,
|
|
[ChatBot, frase, trocada, habilitado]
|
|
);
|
|
});
|
|
|
|
router.patch('/updateTratamentoChatBot', verifyJWT, (req, res) => {
|
|
const idzoetratamentofrases = parseInt(req.body.idzoetratamentofrases);
|
|
const ChatBot = parseInt(req.body.ChatBot);
|
|
const frase = req.body.frase;
|
|
const trocada = req.body.trocada;
|
|
const habilitado = req.body.habilitado ? 1 : 0;
|
|
execSQLQuery(
|
|
`UPDATE zoetratamentofrases SET
|
|
ChatBot = ?,
|
|
frase = ?,
|
|
trocada = ?,
|
|
habilitado = ?
|
|
WHERE idzoetratamentofrases = ?;`,
|
|
res,
|
|
req.originalUrl,
|
|
[ChatBot, frase, trocada, habilitado, idzoetratamentofrases]
|
|
);
|
|
});
|
|
|
|
router.delete(
|
|
'/deleteTratamentoChatBot/:idzoetratamentofrases',
|
|
verifyJWT,
|
|
(req, res) => {
|
|
const idzoetratamentofrases = parseInt(req.params.idzoetratamentofrases);
|
|
execSQLQuery(
|
|
`delete from zoetratamentofrases
|
|
WHERE idzoetratamentofrases = ?;`,
|
|
res,
|
|
req.originalUrl,
|
|
[idzoetratamentofrases]
|
|
);
|
|
}
|
|
);
|
|
|
|
//#endregion
|
|
|
|
// #region Requisição do robô
|
|
|
|
// COMANDOS
|
|
const ComandoRepetirFrase = 'repeat';
|
|
const ComandoOpenConfigMode = 'open config mode';
|
|
const ComandoCloseConfigMode = 'close config mode';
|
|
const ComandoOpenRepeatMode = 'open repeat mode';
|
|
const ComandoCloseRepeatMode = 'close repeat mode';
|
|
const ComandoAjuda = 'explain';
|
|
|
|
const FraseFinal = 'Very good';
|
|
const FraseExemploConfig = 'Try saying, change my name to new name';
|
|
const FraseMudarVariavel = 'change my ';
|
|
const FraseDizerVariavel = 'say my ';
|
|
const FraseEnterSetupMode = 'Config mode has been inited. What can I do?';
|
|
const FraseExitSetupMode = 'Config mode has been closed.';
|
|
const FraseEnterRepeatMode =
|
|
"Repeat after me mode has been inited. Say ' " +
|
|
ComandoCloseRepeatMode +
|
|
"' to exit";
|
|
const FraseServerDown =
|
|
'Ops, server down. Wait a moment and try again please';
|
|
const FraseExitRepeatMode = 'Repeat after me mode has been closed.';
|
|
const FraseComandoIndisponivel = 'Command unavailable while in classes';
|
|
// DAODS PADRAO
|
|
const VelocidadePadrao = 0.75;
|
|
const CoerenciaPadrao = 60;
|
|
const Separador = '<-->';
|
|
const MatriculasTalkFlow = [];
|
|
|
|
var IdiomaZoe = "";
|
|
var experienciaUnilever = false;
|
|
const VozesUnilever = {
|
|
En: "Matthew",
|
|
Pt: "Ricardo",
|
|
Es: "Enrique"
|
|
}
|
|
|
|
|
|
function setIdiomaZoe(idclasses, idusers, callback) {
|
|
mysqlConnection.query(
|
|
`select
|
|
case
|
|
when co.idlanguage = 0 then 'en-US'
|
|
when co.idlanguage = 1 then 'pt-BR'
|
|
when co.idlanguage = 2 then 'es-ES'
|
|
when co.idlanguage = 3 then 'en-US'
|
|
end as courseLanguage,
|
|
co.idtypescourse
|
|
from courses co
|
|
where co.idcourses = (select cl.idcourses from classes cl where cl.idclasses = ${idclasses})`,
|
|
function (error, results, fields) {
|
|
if (!error && results.length > 0) {
|
|
experienciaUnilever = results[0]['idtypescourse'] == 8;
|
|
callback(results[0]['courseLanguage']);
|
|
} else {
|
|
mysqlConnection.query(
|
|
`select
|
|
case
|
|
when co.idlanguage = 0 then 'en-US'
|
|
when co.idlanguage = 1 then 'pt-BR'
|
|
when co.idlanguage = 2 then 'es-ES'
|
|
when co.idlanguage = 3 then 'en-US'
|
|
end as courseLanguage,
|
|
co.idtypescourse
|
|
from users us
|
|
inner join studentCourses sc on sc.idusers = us.user
|
|
inner join courses co on co.idcourses = sc.idcourses
|
|
where us.user = '${idusers}';`, function (err, res, fld) {
|
|
if (!err && res.length > 0) {
|
|
experienciaUnilever = res[0]['idtypescourse'] == 8;
|
|
callback(res[0]['courseLanguage']);
|
|
}
|
|
else {
|
|
experienciaUnilever = false;
|
|
callback("en-US");
|
|
}
|
|
});
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
function logData(mensagem) {
|
|
var data = new Date();
|
|
console.log(
|
|
data.getHours() +
|
|
':' +
|
|
data.getMinutes() +
|
|
':' +
|
|
data.getSeconds() +
|
|
'.' +
|
|
data.getMilliseconds() +
|
|
' - ' +
|
|
mensagem
|
|
);
|
|
}
|
|
|
|
function MontaSQLChatTime(ChatTimeID, Ordem, Seq) {
|
|
return `select R.*, (select ctd.explanation from zoechattimedialog ctd where ctd.idzoechattime = R.idzoechattime and ctd.ordem = R.OrdemAnterior limit 1) as 'Explan' from (
|
|
select
|
|
ctd.*,
|
|
(select ctd2.phrase end from zoechattimedialog ctd2 where ctd2.idzoechattime = ctd.idzoechattime and ctd2.seq = ctd.seq_dir and ctd2.ordem = ctd.ordem + 1 limit 1) as 'ExemploResposta',
|
|
(select ctd2.phrase end from zoechattimedialog ctd2 where ctd2.idzoechattime = ctd.idzoechattime and ctd2.seq = ctd.seq_dir and ctd2.ordem = ctd.ordem + 2 limit 1) as 'ExemploResposta2',
|
|
(select ctd2.phrase end from zoechattimedialog ctd2 where ctd2.idzoechattime = ctd.idzoechattime and ctd2.seq = ctd.seq_dir and ctd2.ordem = (select ctd3.ordem from zoechattimedialog ctd3 where ctd3.idzoechattime = ctd.idzoechattime and ctd3.ordem < ctd.ordem and ctd3.zoetalking = 1 order by ctd3.ordem desc limit 1) limit 1) as 'PerguntaAnterior',
|
|
(select ctd3.ordem from zoechattimedialog ctd3 where ctd3.idzoechattime = ctd.idzoechattime and ctd3.seq = ctd.seq_dir and ctd3.ordem > ctd.ordem /*and ctd3.zoetalking = 0*/ order by ctd3.ordem asc limit 1) as 'ProximaOrdem',
|
|
(select ctd3.ordem from zoechattimedialog ctd3 where ctd3.idzoechattime = ctd.idzoechattime and ctd3.seq = ctd.seq_dir and ctd3.ordem < ctd.ordem /*and ctd3.zoetalking = 1*/ order by ctd3.ordem desc limit 1) as 'OrdemAnterior',
|
|
(select case when count(*) = 1 then 0 else 1 end from zoechattimedialog ctd3 where ctd3.idzoechattime = ctd.idzoechattime and ctd3.seq = ctd.seq_dir and ctd3.ordem = ctd.ordem + 1) as 'Final',
|
|
(select ctd4.zoetalking from zoechattimedialog ctd4 where ctd4.idzoechattime = ctd.idzoechattime and ctd4.seq = ctd.seq_dir and ctd4.ordem > ctd.ordem order by ctd4.ordem asc limit 1) as 'ProximoZoeTalking'
|
|
from zoechattimedialog ctd
|
|
where ctd.idzoechattime = ${ChatTimeID} and ctd.ordem = ${Ordem} and ctd.seq = ${Seq}) R;`;
|
|
}
|
|
|
|
function EscolheFraseNaoEntendeu() {
|
|
const FrasesNaoEntendeuEn = [
|
|
'Sorry, repeat please',
|
|
"I didn't get that, repeat please",
|
|
"I didn't catch that, repeat please",
|
|
'Sorry, say again',
|
|
"I don't understand you",
|
|
];
|
|
const FrasesNaoEntendeuPt = [
|
|
'Desculpe, repita por favor',
|
|
'Não entendi, repita por favor',
|
|
'Não captei, repita por favor',
|
|
'Desculpe, pode repetir?',
|
|
'Eu não entendo você',
|
|
];
|
|
const FrasesNaoEntendeuEs = [
|
|
'Lo siento, repite por favor',
|
|
'No entendí eso, repite por favor',
|
|
'No capté eso, repite por favor',
|
|
'Lo siento, ¿puedes repetir?',
|
|
'No te entiendo',
|
|
];
|
|
let FrasesNaoEntendeu =
|
|
IdiomaZoe == "pt-BR" ? FrasesNaoEntendeuPt :
|
|
IdiomaZoe == "en-US" ? FrasesNaoEntendeuEn :
|
|
IdiomaZoe == "es-ES" ? FrasesNaoEntendeuEs :
|
|
FrasesNaoEntendeuEn;
|
|
|
|
const i = Math.floor(Math.random() * FrasesNaoEntendeu.length - 1) + 1;
|
|
return FrasesNaoEntendeu[i];
|
|
}
|
|
|
|
// Função para gerar um token alfanumérico de 10 caracteres
|
|
function generateToken() {
|
|
const randomBuffer = crypto.randomBytes(5);
|
|
let token = '';
|
|
for (let i = 0; i < randomBuffer.length; i++) {
|
|
token += ('0' + randomBuffer[i]).slice(-2); // Garantir que tenha dois dígitos por byte
|
|
}
|
|
return token.slice(0, 10); // Garantir que o token tenha exatamente 10 dígitos
|
|
}
|
|
|
|
// Estrutura para armazenar dados dos usuários
|
|
const userSessions = {};
|
|
const MAX_USAGE_COUNT = 100;
|
|
const TOKEN_LIFETIME = 3600 * 1000; // 1 hora em milissegundos
|
|
|
|
// Função para obter o token de um usuário ou gerar um novo se necessário
|
|
function getUserToken(matricula, idUnidade) {
|
|
const userKey = `${matricula}-${idUnidade}`;
|
|
|
|
if (!userSessions[userKey]) {
|
|
const token = generateToken();
|
|
userSessions[token] = {
|
|
userKey,
|
|
matricula,
|
|
idUnidade,
|
|
usageCount: 0,
|
|
createdAt: Date.now()
|
|
};
|
|
return token;
|
|
} else {
|
|
// Encontrar a sessão pelo userKey
|
|
const token = Object.keys(userSessions).find(key => userSessions[key].userKey === userKey);
|
|
const session = userSessions[token];
|
|
const currentTime = Date.now();
|
|
|
|
// Verifica se o token deve ser renovado por uso ou tempo
|
|
if (session.usageCount >= MAX_USAGE_COUNT || (currentTime - session.createdAt) > TOKEN_LIFETIME) {
|
|
const newToken = generateToken();
|
|
delete userSessions[token];
|
|
userSessions[newToken] = {
|
|
userKey,
|
|
matricula,
|
|
idUnidade,
|
|
usageCount: 0,
|
|
createdAt: Date.now()
|
|
};
|
|
return newToken;
|
|
}
|
|
return token;
|
|
}
|
|
}
|
|
|
|
// Função para registrar o uso do token
|
|
function useToken(token) {
|
|
console.log('Token Usado: ' + token);
|
|
if (userSessions[token]) {
|
|
userSessions[token].usageCount++;
|
|
console.log(`Uso do token registrado. Contagem atual: ${userSessions[token].usageCount}`);
|
|
} else {
|
|
console.log('Token inválido.');
|
|
}
|
|
}
|
|
|
|
router.post('/recognizeAudio/:token', (req, res) => {
|
|
logData('RecognizeAudio, iniciando');
|
|
let token = req.params.token;
|
|
if (token != Variables('tk_fixed')) {
|
|
res.status(500).send({ status: 'expired' });
|
|
return;
|
|
}
|
|
// RECEBE DADOS DA REQUISIÇÃO
|
|
let form = new formidable.IncomingForm();
|
|
form.maxFileSize = 1024 * 1024 * 1024;
|
|
form.on('file', function (name, file) {});
|
|
form.on('error', function (err) {});
|
|
form.on('aborted', function () {});
|
|
form.parse(req, function (err, fields, files) {
|
|
var Modo = parseInt(fields.Modo);
|
|
var Mensagem = fields.Mensagem || '';
|
|
var Vezes = parseInt(fields.Vezes);
|
|
var ChatTimeID = parseInt(fields.ChatTimeID);
|
|
var Ordem = parseInt(fields.Ordem);
|
|
var Seq = parseInt(fields.Seq);
|
|
var Matricula = parseInt(fields.Matricula);
|
|
var IDUnidade = parseInt(fields.IDUnidade);
|
|
var IDAula = parseInt(fields.IDAula) || 0;
|
|
var IDExercicio = parseInt(fields.IDExercicio);
|
|
|
|
//IdiomaZoe = MatriculasPtBr.includes(Matricula) ? "pt-BR" : "en-US";
|
|
setIdiomaZoe(IDAula, Matricula, function(idioma) {
|
|
IdiomaZoe = idioma;
|
|
logData("Idioma do curso: " + IdiomaZoe + " - Unilever: " + experienciaUnilever);
|
|
|
|
var CaminhoArquivo = '';
|
|
|
|
try {
|
|
CaminhoArquivo = files.Arquivo.path;
|
|
} catch (e) {
|
|
console.log('Sem audio na entrada');
|
|
}
|
|
|
|
// CRIA VARIAVEL COM A DATA ATUAL PARA RENOMEAR O ARQUIVO COM A IDENTIFICACAO DO ALUNO
|
|
let date_ob = new Date();
|
|
let DataHoje =
|
|
date_ob.getDate() +
|
|
'-' +
|
|
(date_ob.getMonth() + 1) +
|
|
'-' +
|
|
date_ob.getFullYear() +
|
|
'-' +
|
|
date_ob.getHours() +
|
|
'-' +
|
|
date_ob.getMinutes() +
|
|
'-' +
|
|
date_ob.getSeconds();
|
|
var NomeArquivo =
|
|
Matricula + '_' + IDUnidade + '_' + IDAula + '_' + DataHoje + '.mp3';
|
|
|
|
// CONVERSACAO LIVRE
|
|
if (Modo == 0) {
|
|
console.log('Conversação Livre');
|
|
|
|
//let SessaoID = Matricula + '' + IDUnidade;
|
|
let SessaoID = getUserToken(Matricula, IDUnidade);
|
|
|
|
if (Mensagem == '') {
|
|
ProcessarAudioEntrada(
|
|
CaminhoArquivo,
|
|
NomeArquivo,
|
|
Modo,
|
|
function (Pergunta, Entendeu) {
|
|
if (Entendeu) {
|
|
let ComandoAluno = VerificaComandoAluno(Pergunta);
|
|
if (ComandoAluno == ComandoOpenConfigMode) {
|
|
// ENTRANDO NO MODO CONFIGURACAO
|
|
EnviaResposta(
|
|
true,
|
|
FraseEnterSetupMode,
|
|
NomeArquivo,
|
|
res,
|
|
FraseEnterSetupMode,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
2,
|
|
0,
|
|
''
|
|
);
|
|
} else if (ComandoAluno == ComandoOpenRepeatMode) {
|
|
// ENTRANDO NO MODO REPETICAO
|
|
EnviaResposta(
|
|
true,
|
|
FraseEnterRepeatMode,
|
|
NomeArquivo,
|
|
res,
|
|
FraseEnterRepeatMode,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
4,
|
|
0,
|
|
''
|
|
);
|
|
} else {
|
|
// SEM COMANDOS
|
|
EnviaPerguntaChatBot(Pergunta, SessaoID, Matricula, function (Resposta) {
|
|
TrataRespostaChatBot(Resposta, function (ResTratada) {
|
|
AtualizarEtapa(
|
|
false,
|
|
Matricula,
|
|
IDUnidade,
|
|
IDAula,
|
|
Ordem,
|
|
Pergunta,
|
|
Resposta,
|
|
'',
|
|
'Sim',
|
|
''
|
|
);
|
|
|
|
EnviaResposta(
|
|
true,
|
|
ResTratada,
|
|
NomeArquivo,
|
|
res,
|
|
ResTratada,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
});
|
|
});
|
|
}
|
|
} else {
|
|
// NAO ENTENDEU A PERGUNTA
|
|
const Frase = EscolheFraseNaoEntendeu();
|
|
EnviaResposta(
|
|
true,
|
|
Frase,
|
|
NomeArquivo,
|
|
res,
|
|
Frase,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
}
|
|
);
|
|
} else {
|
|
EnviaPerguntaChatBot(Mensagem, SessaoID, Matricula, function (Resposta) {
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
Resposta,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Mensagem,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
''
|
|
);
|
|
});
|
|
}
|
|
}
|
|
// CONVERSACAO DIRIGIDA
|
|
else if (Modo == 1) {
|
|
logData('Conversação Dirigida');
|
|
const SQL = MontaSQLChatTime(ChatTimeID, Ordem, Seq);
|
|
mysqlConnection.query(SQL, function (error, ChatTimeDialog, fields) {
|
|
if (!error && ChatTimeDialog && ChatTimeDialog.length > 0) {
|
|
logData('Consulta realizada');
|
|
// FRASE QUE QUEM FALA E A ZOE, LOGO, NAO PROCESSA AUDIO DE ENTRADA
|
|
if (ChatTimeDialog[0]['zoetalking'] == 1) {
|
|
Ordem = ChatTimeDialog[0]['ProximaOrdem'];
|
|
VerificaVariaveisFrase(
|
|
ChatTimeDialog[0]['idzoechattimedialog'],
|
|
ChatTimeDialog[0]['phrase'],
|
|
ChatTimeDialog[0]['phrase'],
|
|
Matricula,
|
|
IDUnidade,
|
|
false,
|
|
function (FraseSubstituida) {
|
|
logData('Variáveis trocadas');
|
|
//console.log(ChatTimeDialog[0]['img']);
|
|
EnviaResposta(
|
|
true,
|
|
FraseSubstituida,
|
|
NomeArquivo,
|
|
res,
|
|
RemoveVariaveisFrase(ChatTimeDialog[0]['ExemploResposta']),
|
|
0,
|
|
ChatTimeDialog[0]['Final'],
|
|
100,
|
|
1,
|
|
ChatTimeDialog[0]['speed'],
|
|
ChatTimeDialog[0]['phrase'],
|
|
Ordem,
|
|
ChatTimeDialog[0]['zoetalking'],
|
|
ChatTimeDialog[0]['ProximoZoeTalking'],
|
|
ChatTimeDialog[0]['idzoevoices'],
|
|
ChatTimeDialog[0]['sub'],
|
|
Modo,
|
|
ChatTimeDialog[0]['seq_dir'],
|
|
ChatTimeDialog[0]['img']
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
// FRASE QUE QUEM FALA E O ALUNO, LOGO, PROCESSA AUDIO DE ENTRADA
|
|
logData('Processar audio de entrada');
|
|
ProcessarAudioEntrada(
|
|
CaminhoArquivo,
|
|
NomeArquivo,
|
|
Modo,
|
|
function (TextoAluno, Entendeu) {
|
|
logData('Audio processado');
|
|
//console.log(TextoAluno);
|
|
|
|
// VERIFICA SE O ALUNO ESTA DANDO ALGUM COMANDO DE SISTEMA
|
|
let ComandoAluno = VerificaComandoAluno(TextoAluno);
|
|
logData('Comando verificado: ' + ComandoAluno);
|
|
if (Entendeu && ComandoAluno != '') {
|
|
if (ComandoAluno == ComandoRepetirFrase) {
|
|
// SE O ALUNO ESTIVER PEDINDO PRA ZOE REPETIR A PERGUNTA ANTERIOR
|
|
logData('REPETINDO');
|
|
VerificaVariaveisFrase(
|
|
ChatTimeDialog[0]['idzoechattimedialog'],
|
|
ChatTimeDialog[0]['PerguntaAnterior'],
|
|
ChatTimeDialog[0]['PerguntaAnterior'],
|
|
Matricula,
|
|
IDUnidade,
|
|
false,
|
|
function (FraseSubstituida) {
|
|
logData('Variáveis da frase verificadas');
|
|
EnviaResposta(
|
|
true,
|
|
'I said, ' + FraseSubstituida,
|
|
NomeArquivo,
|
|
res,
|
|
ChatTimeDialog[0]['phrase'],
|
|
Vezes,
|
|
ChatTimeDialog[0]['Final'],
|
|
100,
|
|
1,
|
|
ChatTimeDialog[0]['speed'],
|
|
ChatTimeDialog[0]['phrase'],
|
|
Ordem,
|
|
ChatTimeDialog[0]['zoetalking'],
|
|
0,
|
|
ChatTimeDialog[0]['idzoevoices'],
|
|
ChatTimeDialog[0]['sub'],
|
|
Modo,
|
|
ChatTimeDialog[0]['seq'],
|
|
ChatTimeDialog[0]['img']
|
|
);
|
|
}
|
|
);
|
|
} else if (ComandoAluno == ComandoAjuda) {
|
|
// SE O ALUNO ESTIVER PEDINDO PRA ZOE AJUDAR COM A FRASE
|
|
logData('EXPLICACAO');
|
|
const FraseExplicacao =
|
|
ChatTimeDialog[0]['Explan'] == '' ||
|
|
!ChatTimeDialog[0]['Explan']
|
|
? 'Try saying ' + ChatTimeDialog[0]['phrase']
|
|
: ChatTimeDialog[0]['Explan'];
|
|
const En =
|
|
ChatTimeDialog[0]['Explan'] == '' ||
|
|
!ChatTimeDialog[0]['Explan']
|
|
? 1
|
|
: ChatTimeDialog[0]['idzoevoices_ex'];
|
|
EnviaResposta(
|
|
true,
|
|
FraseExplicacao,
|
|
NomeArquivo,
|
|
res,
|
|
FraseExplicacao,
|
|
Vezes,
|
|
0,
|
|
100,
|
|
1,
|
|
ChatTimeDialog[0]['speed'],
|
|
TextoAluno,
|
|
Ordem,
|
|
1,
|
|
0,
|
|
En,
|
|
1,
|
|
Modo,
|
|
ChatTimeDialog[0]['seq'],
|
|
ChatTimeDialog[0]['img']
|
|
);
|
|
} else {
|
|
// OUTRO COMANDO QUALQUER
|
|
EnviaResposta(
|
|
true,
|
|
FraseComandoIndisponivel,
|
|
NomeArquivo,
|
|
res,
|
|
FraseComandoIndisponivel,
|
|
Vezes,
|
|
0,
|
|
100,
|
|
1,
|
|
Velocidade,
|
|
TextoAluno,
|
|
Ordem,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
Seq,
|
|
''
|
|
);
|
|
}
|
|
} else if (!Entendeu) {
|
|
logData('NAO ENTENDEU');
|
|
Vezes++;
|
|
|
|
let Resposta = EscolheFraseNaoEntendeu();
|
|
|
|
AtualizarEtapa(
|
|
false,
|
|
Matricula,
|
|
IDUnidade,
|
|
IDAula,
|
|
Ordem,
|
|
TextoAluno,
|
|
Resposta,
|
|
ChatTimeDialog[0]['phrase'],
|
|
'Não',
|
|
'actualItem'
|
|
);
|
|
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
RemoveVariaveisFrase(ChatTimeDialog[0]['phrase']),
|
|
Vezes,
|
|
ChatTimeDialog[0]['Final'],
|
|
0,
|
|
0,
|
|
ChatTimeDialog[0]['speed'],
|
|
TextoAluno,
|
|
Ordem,
|
|
ChatTimeDialog[0]['zoetalking'],
|
|
0,
|
|
ChatTimeDialog[0]['idzoevoices'],
|
|
ChatTimeDialog[0]['sub'],
|
|
Modo,
|
|
ChatTimeDialog[0]['seq'],
|
|
ChatTimeDialog[0]['img']
|
|
);
|
|
}
|
|
// SE O ALUNO ESTIVER RESPONDENDO A PERGUNTA ANTERIOR
|
|
else {
|
|
logData('PROCESSANDO');
|
|
mysqlConnection.query(
|
|
`select sentence, seq_dir from zoechattimesentences where idzoechattimedialog in (select distinct idzoechattimedialog from zoechattimedialog where idzoechattime = ${ChatTimeID} and ordem = ${Ordem});`,
|
|
function (error, Sentencas, fields) {
|
|
logData('Consulta de sentenças realizada');
|
|
VerificaPronunciaUsuario(
|
|
Sentencas,
|
|
TextoAluno,
|
|
ChatTimeDialog[0]['percent'],
|
|
function (Porcentagem, Seq_Dir) {
|
|
logData('Pronúncia verificada');
|
|
let Resposta = '';
|
|
let ExResposta = '';
|
|
let Validou = 0;
|
|
let Final = 0;
|
|
if (Porcentagem >= ChatTimeDialog[0]['percent']) {
|
|
// REQUISITAR A PROXIMA FRASE
|
|
const SQL = MontaSQLChatTime(
|
|
ChatTimeID,
|
|
ChatTimeDialog[0]['ProximaOrdem'],
|
|
Seq_Dir
|
|
);
|
|
mysqlConnection.query(
|
|
SQL,
|
|
function (error, ChatTimeDialogRes, fields) {
|
|
logData(
|
|
'Consulta da próxima frase realizada'
|
|
);
|
|
Ordem = ChatTimeDialogRes[0]['ProximaOrdem'];
|
|
Final = ChatTimeDialogRes[0]['Final'];
|
|
Resposta = ChatTimeDialogRes[0]['phrase'];
|
|
ExResposta = RemoveVariaveisFrase(
|
|
ChatTimeDialogRes[0]['ExemploResposta']
|
|
);
|
|
Seq_Dir = ChatTimeDialogRes[0]['seq_dir'];
|
|
Vezes = 0;
|
|
Validou = 1;
|
|
|
|
AtualizarEtapa(
|
|
true,
|
|
Matricula,
|
|
IDUnidade,
|
|
IDAula,
|
|
Ordem,
|
|
TextoAluno,
|
|
Resposta,
|
|
ExResposta,
|
|
'Sim',
|
|
'actualItem'
|
|
);
|
|
|
|
VerificaVariaveisFrase(
|
|
ChatTimeDialog[0]['idzoechattimedialog'],
|
|
TextoAluno,
|
|
ChatTimeDialog[0]['phrase'],
|
|
Matricula,
|
|
IDUnidade,
|
|
true,
|
|
function (FraseSubstituidaAluno) {
|
|
VerificaVariaveisFrase(
|
|
ChatTimeDialog[0][
|
|
'idzoechattimedialog'
|
|
],
|
|
TextoAluno,
|
|
Resposta,
|
|
Matricula,
|
|
IDUnidade,
|
|
false,
|
|
function (FraseSubstituidaZoe) {
|
|
EnviaResposta(
|
|
Resposta == null ? false : true,
|
|
FraseSubstituidaZoe,
|
|
NomeArquivo,
|
|
res,
|
|
ExResposta,
|
|
Vezes,
|
|
Final,
|
|
Porcentagem,
|
|
Validou,
|
|
VelocidadePadrao,
|
|
TextoAluno,
|
|
Ordem,
|
|
ChatTimeDialogRes[0]['zoetalking'],
|
|
ChatTimeDialogRes[0][
|
|
'ProximoZoeTalking'
|
|
],
|
|
ChatTimeDialogRes[0]['idzoevoices'],
|
|
ChatTimeDialogRes[0]['sub'],
|
|
Modo,
|
|
Seq_Dir,
|
|
ChatTimeDialogRes[0]['img']
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
logData(
|
|
'Não atingiu a porcentagem mínima: ' +
|
|
Porcentagem +
|
|
' de ' +
|
|
ChatTimeDialog[0]['percent']
|
|
);
|
|
Resposta = EscolheFraseNaoEntendeu();
|
|
ExResposta = RemoveVariaveisFrase(
|
|
ChatTimeDialog[0]['phrase']
|
|
);
|
|
Vezes++;
|
|
Validou = 0;
|
|
Final = 0;
|
|
|
|
AtualizarEtapa(
|
|
false,
|
|
Matricula,
|
|
IDUnidade,
|
|
IDAula,
|
|
Ordem,
|
|
TextoAluno,
|
|
Resposta,
|
|
ExResposta,
|
|
'Não',
|
|
'actualItem'
|
|
);
|
|
|
|
EnviaResposta(
|
|
Resposta == null ? false : true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
ExResposta,
|
|
Vezes,
|
|
Final,
|
|
Porcentagem,
|
|
Validou,
|
|
VelocidadePadrao,
|
|
TextoAluno,
|
|
Ordem,
|
|
ChatTimeDialog[0]['zoetalking'],
|
|
0,
|
|
ChatTimeDialog[0]['idzoevoices'],
|
|
ChatTimeDialog[0]['sub'],
|
|
Modo,
|
|
ChatTimeDialog[0]['seq'],
|
|
ChatTimeDialog[0]['img']
|
|
);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
} else {
|
|
console.log('Erro ao requisitar ChatTime');
|
|
console.log(error);
|
|
console.log('Consulta:');
|
|
console.log(SQL);
|
|
EnviaResposta(
|
|
true,
|
|
FraseServerDown,
|
|
NomeArquivo,
|
|
res,
|
|
'',
|
|
Vezes,
|
|
0,
|
|
0,
|
|
0,
|
|
VelocidadePadrao,
|
|
'',
|
|
Ordem,
|
|
1,
|
|
1,
|
|
1,
|
|
1,
|
|
Modo,
|
|
Seq,
|
|
''
|
|
);
|
|
}
|
|
});
|
|
}
|
|
// MODO CONFIGURACAO
|
|
else if (Modo == 2) {
|
|
console.log('Modo Configuração');
|
|
ProcessarAudioEntrada(
|
|
CaminhoArquivo,
|
|
NomeArquivo,
|
|
Modo,
|
|
function (Pergunta, Entendeu) {
|
|
if (Entendeu) {
|
|
let ComandoAluno = VerificaComandoAluno(Pergunta);
|
|
if (ComandoAluno == ComandoCloseConfigMode) {
|
|
// SAINDO DO MODO CONFIGURACAO
|
|
EnviaResposta(
|
|
true,
|
|
FraseExitSetupMode,
|
|
NomeArquivo,
|
|
res,
|
|
FraseExitSetupMode,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
0,
|
|
0,
|
|
''
|
|
);
|
|
} else {
|
|
// SEM COMANDOS DO ALUNO
|
|
ModoConfiguracao(
|
|
Pergunta,
|
|
NomeArquivo,
|
|
res,
|
|
Matricula,
|
|
IDUnidade
|
|
);
|
|
}
|
|
} else {
|
|
EnviaResposta(
|
|
true,
|
|
EscolheFraseNaoEntendeu(),
|
|
NomeArquivo,
|
|
res,
|
|
FraseExemploConfig,
|
|
0,
|
|
0,
|
|
0,
|
|
0,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
0,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
// MODO EXERCICIO DE PRONUNCIA
|
|
else if (Modo == 3) {
|
|
console.log('Exercício de Pronúncia');
|
|
// SEM ARQUIVO DE AUDIO, LOGO, A ZOE IRA PRONUNCIAR A PERGUNTA
|
|
const SQL = `select
|
|
ex.description,
|
|
eq.*
|
|
from exercisequestions eq
|
|
inner join exercises ex on ex.idexercises = eq.idexercises
|
|
where ex.idexercises = ${IDExercicio};`;
|
|
mysqlConnection.query(SQL, function (error, Questoes, fields) {
|
|
if (!error && Questoes && Questoes.length > 0) {
|
|
if (Ordem > Questoes.length - 1 || Ordem < 0) {
|
|
console.log(SQL);
|
|
console.log('Ordem: ' + Ordem);
|
|
console.log('Questoes: ' + Questoes.length);
|
|
EnviaResposta(
|
|
true,
|
|
'Trying again',
|
|
NomeArquivo,
|
|
res,
|
|
'',
|
|
0,
|
|
0,
|
|
0,
|
|
0,
|
|
VelocidadePadrao,
|
|
'',
|
|
0,
|
|
1,
|
|
1,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
return;
|
|
}
|
|
let Enunciado = Questoes[Ordem]['description'];
|
|
let Velocidade =
|
|
Questoes[Ordem]['content'].split(Separador)[1] ||
|
|
VelocidadePadrao;
|
|
let Coerencia =
|
|
Questoes[Ordem]['content'].split(Separador)[2] || CoerenciaPadrao;
|
|
let ExResposta = Questoes[Ordem]['content'].split(Separador)[0];
|
|
let Pergunta =
|
|
(Ordem == 0 && Vezes == 0 ? Enunciado + '. ' : '') + ExResposta;
|
|
if (CaminhoArquivo == '' || Mensagem != '') {
|
|
// SEM ARQUIVO DE AUDIO, LOGO, A ZOE IRA PRONUNCIAR O EXERCICIO
|
|
EnviaResposta(
|
|
true,
|
|
Pergunta,
|
|
NomeArquivo,
|
|
res,
|
|
ExResposta,
|
|
0,
|
|
0,
|
|
Coerencia,
|
|
1,
|
|
Velocidade,
|
|
'',
|
|
Ordem,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
} else {
|
|
// COM ARQUIVO DE AUDIO, LOGO, A ZOE IRA PROCESSAR O AUDIO DO ALUNO
|
|
ProcessarAudioEntrada(
|
|
CaminhoArquivo,
|
|
NomeArquivo,
|
|
Modo,
|
|
function (TextoAluno, Entendeu) {
|
|
// VERIFICA SE O ALUNO ESTA DANDO ALGUM COMANDO DE SISTEMA
|
|
let ComandoAluno = VerificaComandoAluno(TextoAluno);
|
|
if (Entendeu && ComandoAluno != '') {
|
|
if (ComandoAluno == ComandoRepetirFrase) {
|
|
// SE O ALUNO ESTIVER PEDINDO PRA ZOE REPETIR A PERGUNTA ANTERIOR
|
|
console.log('REPETINDO');
|
|
EnviaResposta(
|
|
true,
|
|
'I said, ' + Pergunta,
|
|
NomeArquivo,
|
|
res,
|
|
Pergunta,
|
|
Vezes,
|
|
0,
|
|
100,
|
|
1,
|
|
Velocidade,
|
|
TextoAluno,
|
|
Ordem,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
} else {
|
|
// OUTRO COMANDO QUALQUER
|
|
EnviaResposta(
|
|
true,
|
|
FraseComandoIndisponivel,
|
|
NomeArquivo,
|
|
res,
|
|
FraseComandoIndisponivel,
|
|
Vezes,
|
|
0,
|
|
100,
|
|
1,
|
|
Velocidade,
|
|
TextoAluno,
|
|
Ordem,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
} else {
|
|
let Frase = { sentence: ExResposta, seq_dir: 0 };
|
|
VerificaPronunciaUsuario(
|
|
[Frase],
|
|
TextoAluno,
|
|
Coerencia,
|
|
function (Porcentagem) {
|
|
let Resposta = '';
|
|
let Validou = 0;
|
|
let Final = 0;
|
|
let IndexQuestao = Ordem;
|
|
if (Entendeu && Porcentagem >= Coerencia) {
|
|
Final = Ordem == Questoes.length - 1 ? 1 : 0;
|
|
if (Final == 1) Resposta = FraseFinal;
|
|
else {
|
|
Ordem++;
|
|
Resposta =
|
|
Questoes[Ordem]['content'].split(Separador)[0];
|
|
ExResposta =
|
|
Questoes[Ordem]['content'].split(Separador)[0];
|
|
}
|
|
Validou = 1;
|
|
Vezes = 0;
|
|
} else {
|
|
Resposta = "Try again saying: '" + ExResposta + "'";
|
|
Validou = 0;
|
|
Final = 0;
|
|
Vezes++;
|
|
}
|
|
if (Entendeu) {
|
|
AtualizarEtapa(
|
|
true,
|
|
Matricula,
|
|
IDUnidade,
|
|
IDAula,
|
|
Ordem,
|
|
Pergunta,
|
|
Resposta,
|
|
ExResposta,
|
|
'Sim',
|
|
'actualAnswer'
|
|
);
|
|
mysqlConnection.query(
|
|
`insert into exerciseanswers (idexercisequestions, hasmedia, content, iscorrect, orientation) values (?, 0, ?, ?, 0);`,
|
|
[
|
|
Questoes[IndexQuestao]['idexercisequestions'],
|
|
TextoAluno,
|
|
Validou,
|
|
],
|
|
function (errAnswer, resAnswer, fieAnswer) {
|
|
if (errAnswer) console.log(errAnswer);
|
|
let date_answered =
|
|
date_ob.getDate() +
|
|
'/' +
|
|
(date_ob.getMonth() + 1) +
|
|
'/' +
|
|
date_ob.getFullYear();
|
|
mysqlConnection.query(
|
|
`select idusergivenanswers from usergivenanswers order by idusergivenanswers desc limit 1;`,
|
|
function (errUG, resUG, fieUG) {
|
|
mysqlConnection.query(
|
|
`insert into usergivenanswers (idusergivenanswers, idusers, idexerciseanswers, date_answered, fixed, idclasses, idunits) values (?, ?, ?, ?, 1, ?, ?);`,
|
|
[
|
|
resUG[0]['idusergivenanswers'],
|
|
Matricula,
|
|
resAnswer['insertId'],
|
|
date_answered,
|
|
IDAula,
|
|
IDUnidade,
|
|
],
|
|
function (
|
|
errUserAnswer,
|
|
resUserAnswer,
|
|
fieUserAnswer
|
|
) {
|
|
if (errUserAnswer)
|
|
console.log(errUserAnswer);
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
ExResposta,
|
|
Vezes,
|
|
Final,
|
|
Porcentagem,
|
|
Validou,
|
|
Velocidade,
|
|
TextoAluno,
|
|
Ordem,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
AtualizarEtapa(
|
|
false,
|
|
Matricula,
|
|
IDUnidade,
|
|
IDAula,
|
|
Ordem,
|
|
Pergunta,
|
|
Resposta,
|
|
ExResposta,
|
|
'Não',
|
|
'actualAnswer'
|
|
);
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
ExResposta,
|
|
Vezes,
|
|
Final,
|
|
Porcentagem,
|
|
Validou,
|
|
Velocidade,
|
|
TextoAluno,
|
|
Ordem,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
} else {
|
|
console.log('Erro ao requisitar Exercicio de Pronuncia');
|
|
console.log(error);
|
|
console.log('Consulta:');
|
|
console.log(SQL);
|
|
EnviaResposta(
|
|
true,
|
|
FraseServerDown,
|
|
NomeArquivo,
|
|
res,
|
|
'',
|
|
Vezes,
|
|
0,
|
|
0,
|
|
0,
|
|
VelocidadePadrao,
|
|
'',
|
|
Ordem,
|
|
1,
|
|
1,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
});
|
|
}
|
|
// MODO DE REPETICAO
|
|
else if (Modo == 4) {
|
|
console.log('MODO DE REPETICAO');
|
|
ProcessarAudioEntrada(
|
|
CaminhoArquivo,
|
|
NomeArquivo,
|
|
Modo,
|
|
function (Pergunta, Entendeu) {
|
|
if (Entendeu) {
|
|
let ComandoAluno = VerificaComandoAluno(Pergunta);
|
|
if (ComandoAluno == ComandoCloseRepeatMode) {
|
|
// SAINDO DO MODO REPETICAO
|
|
EnviaResposta(
|
|
true,
|
|
FraseExitRepeatMode,
|
|
NomeArquivo,
|
|
res,
|
|
FraseExitRepeatMode,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
0,
|
|
0,
|
|
''
|
|
);
|
|
} else {
|
|
// SEM COMANDOS
|
|
EnviaResposta(
|
|
true,
|
|
Pergunta,
|
|
NomeArquivo,
|
|
res,
|
|
Pergunta,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
} else {
|
|
// NAO ENTENDEU A PERGUNTA
|
|
const Frase = EscolheFraseNaoEntendeu();
|
|
EnviaResposta(
|
|
true,
|
|
Frase,
|
|
NomeArquivo,
|
|
res,
|
|
Frase,
|
|
0,
|
|
0,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
1,
|
|
Modo,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
});
|
|
});
|
|
|
|
|
|
});
|
|
|
|
function AtualizarEtapa(
|
|
AtualizaBanco,
|
|
idusers,
|
|
idunits,
|
|
idclasses,
|
|
ordem,
|
|
Entendeu,
|
|
Resposta,
|
|
ExResposta,
|
|
Validou,
|
|
Campo
|
|
) {
|
|
if (AtualizaBanco) {
|
|
logData('Atualizando etapa');
|
|
mysqlConnection.query(
|
|
`update stepclass set ${Campo} = ${ordem} where idusers = ${idusers} and idunits = ${idunits} and idclasses = ${idclasses};`,
|
|
function (error, results, fields) {
|
|
if (!error) {
|
|
logData(
|
|
`Etapa atualizada com sucesso - Matrícula: ${idusers}, Unidade: ${idunits}, Aula: ${idclasses}`
|
|
);
|
|
} else {
|
|
logData(
|
|
`Erro ao atualizar etapa - Matrícula: ${idusers}, Unidade: ${idunits}, Aula: ${idclasses}`
|
|
);
|
|
}
|
|
logData(
|
|
`Validou: "${Validou}", Zoe Entendeu: "${Entendeu}", Resposta Zoe: "${Resposta}", Exemplo Resposta: "${ExResposta}"`
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
logData(
|
|
`Validou: "${Validou}", Zoe Entendeu: "${Entendeu}", Resposta Zoe: "${Resposta}", Exemplo Resposta: "${ExResposta}"`
|
|
);
|
|
}
|
|
}
|
|
|
|
function VerificaComandoAluno(TextoAluno) {
|
|
let Comando = '';
|
|
|
|
if (TextoAluno.includes(ComandoRepetirFrase)) Comando = ComandoRepetirFrase;
|
|
else if (TextoAluno.includes(ComandoOpenConfigMode))
|
|
Comando = ComandoOpenConfigMode;
|
|
else if (TextoAluno.includes(ComandoCloseConfigMode))
|
|
Comando = ComandoCloseConfigMode;
|
|
else if (TextoAluno.includes(ComandoOpenRepeatMode))
|
|
Comando = ComandoOpenRepeatMode;
|
|
else if (TextoAluno.includes(ComandoCloseRepeatMode))
|
|
Comando = ComandoCloseRepeatMode;
|
|
else if (TextoAluno.includes(ComandoAjuda)) Comando = ComandoAjuda;
|
|
|
|
return Comando;
|
|
}
|
|
|
|
function ProcessarAudioEntrada(CaminhoArquivo, NomeArquivo, Modo, callback) {
|
|
const fs = require('fs');
|
|
const CaminhoArquivoServidor =
|
|
Variables('src_media') + 'audioZoe2/' + NomeArquivo;
|
|
fs.rename(CaminhoArquivo, CaminhoArquivoServidor, function (err) {
|
|
if (err) throw err;
|
|
logData('Arquivo renomeado');
|
|
const shell = require('shelljs');
|
|
|
|
mysqlConnection.query(
|
|
'select STTmode, PythonVersion from config;',
|
|
function (error, Config, fields) {
|
|
logData('Consulta config realizada');
|
|
const STTmode = Config[0]['STTmode'];
|
|
const PythonVersion = Config[0]['PythonVersion'];
|
|
// CONVERTER O .wav PARA TEXTO
|
|
var audioTotext = null;
|
|
|
|
if (STTmode == 1) {
|
|
// GOOGLE SPEECH RECOGNITION NODE
|
|
logData('Google Speech Recognition');
|
|
AudioParaTexto(CaminhoArquivoServidor, function (Texto) {
|
|
logData('Response do Google recebido: ' + Texto);
|
|
VerificaTextoAudio(Texto, function (Pergunta, Entendeu) {
|
|
logData('Texto verificado');
|
|
callback(Pergunta, Entendeu);
|
|
//uploadFileToBucket(CaminhoArquivoServidor);
|
|
});
|
|
});
|
|
} else if (STTmode == 2) {
|
|
// GOOGLE SPEECH RECOGNITION FREE
|
|
console.log('inicio do google speech free --- RecognizeAudio');
|
|
let Comando = `${PythonVersion} ${Variables(
|
|
'src_media'
|
|
)}assets/audio_to_text2.py ${NomeArquivo}`;
|
|
audioTotext = shell.exec(Comando);
|
|
VerificaTextoAudio(
|
|
audioTotext.stdout,
|
|
function (Pergunta, Entendeu) {
|
|
callback(Pergunta, Entendeu);
|
|
//uploadFileToBucket(CaminhoArquivoServidor);
|
|
console.log('inicio do google speech free --- RecognizeAudio');
|
|
}
|
|
);
|
|
} else if (STTmode == 3) {
|
|
// GOOGLE SPEECH RECOGNITION PYTHON
|
|
let Comando = `export GOOGLE_APPLICATION_CREDENTIALS="/var/www/zoeGoogleCloudSpeech.json"; ${PythonVersion} ${Variables(
|
|
'src_media'
|
|
)}assets/speech_cloud.py ${NomeArquivo}`;
|
|
audioTotext = shell.exec(Comando);
|
|
VerificaTextoAudio(
|
|
audioTotext.stdout,
|
|
function (Pergunta, Entendeu) {
|
|
callback(Pergunta, Entendeu);
|
|
//uploadFileToBucket(CaminhoArquivoServidor);
|
|
}
|
|
);
|
|
} else if (STTmode == 4) {
|
|
// WATSON
|
|
|
|
shell.exec(
|
|
`ffmpeg -loglevel panic -i ${CaminhoArquivoServidor} -acodec pcm_s16le -ar 44100 ${
|
|
CaminhoArquivoServidor.split('.')[0]
|
|
}.wav`,
|
|
function (Sucesso) {
|
|
const fs = require('fs');
|
|
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
|
|
const { IamAuthenticator } = require('ibm-watson/auth');
|
|
|
|
const speechToText = new SpeechToTextV1({
|
|
authenticator: new IamAuthenticator({ apikey: STTWatsonKey }),
|
|
serviceUrl: STTWatsonService,
|
|
});
|
|
|
|
const params = {
|
|
audio: fs.createReadStream(
|
|
CaminhoArquivoServidor.split('.')[0] + '.wav'
|
|
),
|
|
contentType: 'audio/l16; rate=44100',
|
|
};
|
|
|
|
speechToText
|
|
.recognize(params)
|
|
.then((response) => {
|
|
let Transcript = JSON.stringify(response.result, null, 2);
|
|
let TextoAudio = '';
|
|
let Confidence = '';
|
|
if (JSON.parse(Transcript).results.length > 0) {
|
|
TextoAudio =
|
|
JSON.parse(Transcript).results[0].alternatives[0]
|
|
.transcript;
|
|
Confidence =
|
|
JSON.parse(Transcript).results[0].alternatives[0]
|
|
.confidence;
|
|
}
|
|
//console.log("Transcript: " + TextoAudio + " - Confidence: " + Confidence);
|
|
VerificaTextoAudio(
|
|
TextoAudio,
|
|
function (Pergunta, Entendeu) {
|
|
callback(Pergunta, Entendeu);
|
|
}
|
|
);
|
|
})
|
|
.catch((err) => {
|
|
console.log(err);
|
|
VerificaTextoAudio('', function (Pergunta, Entendeu) {
|
|
callback(Pergunta, Entendeu);
|
|
//uploadFileToBucket(CaminhoArquivoServidor);
|
|
});
|
|
});
|
|
}
|
|
);
|
|
}
|
|
}
|
|
);
|
|
});
|
|
}
|
|
|
|
async function AudioParaTexto(CaminhoArquivo, callback) {
|
|
// HEADERS DE UM WAV EM: http://soundfile.sapp.org/doc/WaveFormat/
|
|
const speech = require('@google-cloud/speech');
|
|
const fs = require('fs');
|
|
const client = new speech.SpeechClient({
|
|
projectId: 'zoerobot-1581961113901',
|
|
keyFilename: '/var/www/zoeGoogleCloudSpeech.json',
|
|
});
|
|
|
|
const file = fs.readFileSync(CaminhoArquivo);
|
|
const audioBytes = file.toString('base64');
|
|
const channels = file[22];
|
|
const RateHertz = parseInt(
|
|
file[24].toString() +
|
|
file[25].toString() +
|
|
file[26].toString() +
|
|
file[27].toString()
|
|
);
|
|
|
|
const audio = {
|
|
content: audioBytes,
|
|
};
|
|
const config = {
|
|
encoding: 'LINEAR16',
|
|
//sampleRateHertz: RateHertz,
|
|
languageCode: IdiomaZoe,
|
|
audioChannelCount: channels,
|
|
};
|
|
const request = {
|
|
audio: audio,
|
|
config: config,
|
|
};
|
|
|
|
const [response] = await client.recognize(request);
|
|
const transcription = response.results
|
|
.map((result) => result.alternatives[0].transcript)
|
|
.join('\n');
|
|
//console.log(`Transcription: ${transcription}`);
|
|
callback(transcription);
|
|
}
|
|
|
|
function VerificaTextoAudio(Pergunta, callback) {
|
|
// Remove o \r\n do final da frase
|
|
for (let i = 0; i < 2; i++) {
|
|
if (
|
|
Pergunta[Pergunta.length - 1] == '\r' ||
|
|
Pergunta[Pergunta.length - 1] == '\n'
|
|
) {
|
|
Pergunta = Pergunta.substring(0, Pergunta.length - 1);
|
|
}
|
|
}
|
|
|
|
//console.log("Audio para Texto: " + Pergunta);
|
|
|
|
let Entendeu = true;
|
|
|
|
if (
|
|
Pergunta.includes(
|
|
'Google Speech Recognition could not understand audio'
|
|
) ||
|
|
Pergunta.includes(
|
|
'Could not request results from Google Speech Recognition service'
|
|
) ||
|
|
Pergunta == ''
|
|
) {
|
|
Entendeu = false;
|
|
Pergunta = EscolheFraseNaoEntendeu();
|
|
}
|
|
|
|
callback(Pergunta, Entendeu);
|
|
}
|
|
|
|
function VerificaPronunciaUsuario(ListaSentencas, TextoAluno, Coerencia, callback) {
|
|
logData('Verificando pronúncia do usuário');
|
|
|
|
for (let i = 0; i < ListaSentencas.length; i++) {
|
|
ListaSentencas[i]['sentence'] = ReplaceAll(
|
|
ListaSentencas[i]['sentence'].toLowerCase(),
|
|
[',', '-', '_', '!', '?', "'", '.'],
|
|
['', '', '', '', '', '', ''],
|
|
15
|
|
);
|
|
}
|
|
|
|
TextoAluno = ReplaceAll(
|
|
TextoAluno.toLowerCase(),
|
|
[',', '-', '_', '!', '?', "'", '.'],
|
|
['', '', '', '', '', '', ''],
|
|
15
|
|
);
|
|
|
|
let Porcentagem = 0;
|
|
let IndexSentenca = 0;
|
|
|
|
mysqlConnection.query(
|
|
'select checkSentence, PythonVersion from config;',
|
|
function (error, Config, fields) {
|
|
logData('Consulta config realizada');
|
|
const CheckSentence = Config[0]['checkSentence'];
|
|
const PythonVersion = Config[0]['PythonVersion'];
|
|
|
|
loopCheckSentence(0, 0, IndexSentenca, ListaSentencas, TextoAluno, PythonVersion, CheckSentence, Coerencia, function(percent, index) {
|
|
Porcentagem = percent;
|
|
IndexSentenca = index;
|
|
callback(Porcentagem, ListaSentencas[IndexSentenca]['seq_dir']);
|
|
});
|
|
|
|
/*runPythonScript(`${PythonVersion} ${Variables('src_media')}assets/${CheckSentence} \"${
|
|
ListaSentencas[IndexSentenca]['sentence']
|
|
}\" \"${TextoAluno}\"`).then(percent => {
|
|
logData('Percentual de coerencia: ' + percent);
|
|
Porcentagem = percent;
|
|
callback(Porcentagem, ListaSentencas[IndexSentenca]['seq_dir']);
|
|
});*/
|
|
|
|
}
|
|
);
|
|
}
|
|
|
|
function loopCheckSentence(Porcentagem, Index, IndexSentenca, ListaSentencas, TextoAluno, PythonVersion, CheckSentence, Coerencia, callback) {
|
|
if (IndexSentenca < ListaSentencas.length) {
|
|
runPythonScript(`${PythonVersion} ${Variables('src_media')}assets/${CheckSentence} \"${
|
|
ListaSentencas[IndexSentenca]['sentence']
|
|
}\" \"${TextoAluno}\"`).then(percent => {
|
|
logData('Teste ' + (IndexSentenca + 1) + ' de ' + ListaSentencas.length + ' - Coerencia ' + percent + ' de ' + Coerencia);
|
|
if (percent >= Coerencia) {
|
|
Porcentagem = percent;
|
|
Index = IndexSentenca;
|
|
callback(Porcentagem, Index);
|
|
}
|
|
else {
|
|
if (percent > Porcentagem) {
|
|
Porcentagem = percent;
|
|
Index = IndexSentenca;
|
|
}
|
|
IndexSentenca++;
|
|
loopCheckSentence(Porcentagem, Index, IndexSentenca, ListaSentencas, TextoAluno, PythonVersion, CheckSentence, Coerencia, callback);
|
|
}
|
|
});
|
|
}
|
|
else {
|
|
callback(Porcentagem, Index);
|
|
}
|
|
}
|
|
|
|
async function runPythonScript(script) {
|
|
const shell = require('shelljs');
|
|
return new Promise((resolve, reject) => {
|
|
shell.exec(script, function (code, stdout, stderr) {
|
|
if (code === 0) {
|
|
const percent = parseFloat(stdout);
|
|
resolve(percent);
|
|
} else {
|
|
reject(stderr);
|
|
}
|
|
}
|
|
);
|
|
});
|
|
}
|
|
|
|
function CompareStrings(str1, str2) {
|
|
let pairs1 = WordLetterPairs(str1.toLowerCase());
|
|
let pairs2 = WordLetterPairs(str2.toLowerCase());
|
|
|
|
let intersection = 0;
|
|
let union = pairs1.length + pairs2.length;
|
|
|
|
for (let i = 0; i < pairs1.length; i++) {
|
|
for (let j = 0; j < pairs2.length; j++) {
|
|
if (pairs1[i] == pairs2[j]) {
|
|
intersection++;
|
|
pairs2.splice(j, 1);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return (2.0 * intersection) / union;
|
|
}
|
|
|
|
function WordLetterPairs(str) {
|
|
let AllPairs = [];
|
|
let Words = str.split(' ');
|
|
for (let w = 0; w < Words.length; w++) {
|
|
if (Words[w]) {
|
|
let PairsInWord = LetterPairs(Words[w]);
|
|
for (let p = 0; p < PairsInWord.length; p++) {
|
|
AllPairs.push(PairsInWord[p]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return AllPairs;
|
|
}
|
|
|
|
function LetterPairs(str) {
|
|
let numPairs = str.length - 1;
|
|
let pairs = [];
|
|
for (let i = 0; i < numPairs; i++) {
|
|
pairs[i] = str.substring(i, 2);
|
|
}
|
|
|
|
return pairs;
|
|
}
|
|
|
|
function RemoveVariaveisFrase(Frase) {
|
|
let NovaFrase = '';
|
|
if (Frase && Frase.includes('+')) {
|
|
let Trechos = Frase.split('+');
|
|
for (let i = 0; i < Trechos.length; i++) {
|
|
if (i % 2 == 0) NovaFrase += Trechos[i];
|
|
else NovaFrase += '_____';
|
|
}
|
|
} else {
|
|
NovaFrase = Frase;
|
|
}
|
|
|
|
return NovaFrase;
|
|
}
|
|
|
|
function VerificaVariaveisFrase(
|
|
idzoechattimedialog,
|
|
FraseEntrada,
|
|
FraseComparada,
|
|
Matricula,
|
|
IDUnidade,
|
|
AlunoFalando,
|
|
callback
|
|
) {
|
|
logData('Verificando se existem variáveis na frase');
|
|
//FraseEntrada = ReplaceAll(FraseEntrada.toLowerCase(), [",", "-", "_", "!", "?", "'"], ["", "", "", "", "", ""], 15);
|
|
//FraseComparada = ReplaceAll(FraseComparada.toLowerCase(), [",", "-", "_", "!", "?", "'"], ["", "", "", "", "", ""], 15);
|
|
let FraseSubstituida = '';
|
|
//console.log(FraseEntrada);
|
|
//console.log(FraseComparada);
|
|
// SE HOUVER VARIAVEL NA FRASE
|
|
if (FraseComparada && FraseComparada.includes('+')) {
|
|
let PalavrasFrase = FraseComparada.split(' ');
|
|
let VariaveisFrase = [];
|
|
let WhereVariables = '(';
|
|
for (let i = 0; i < PalavrasFrase.length; i++) {
|
|
if (PalavrasFrase[i].includes('+')) {
|
|
const Variavel = PalavrasFrase[i].split('+')[1];
|
|
VariaveisFrase.push({
|
|
idalexavariables: 0,
|
|
description: Variavel,
|
|
valuecli: 'UNKNOW',
|
|
});
|
|
if (WhereVariables != '(') WhereVariables += ',';
|
|
WhereVariables += "'" + Variavel + "'";
|
|
}
|
|
}
|
|
WhereVariables += ')';
|
|
|
|
//console.log(WhereVariables);
|
|
|
|
const sqlVariaveis = `select avr.description, auv.* from alexauservariables auv inner join alexavariables avr on avr.idalexavariables = auv.idalexavariables where auv.idusers = ${Matricula} and auv.idunits = ${IDUnidade} and avr.description in ${WhereVariables};`;
|
|
//console.log(sqlVariaveis);
|
|
mysqlConnection.query(
|
|
sqlVariaveis,
|
|
function (error, VariaveisEncontradas, fields) {
|
|
logData('Consulta de variáveis realizada');
|
|
//console.log(VariaveisEncontradas);
|
|
|
|
let Encontrou = false;
|
|
// EXISTEM DADOS GRAVADOS NO BANCO PARA AS VARIAVEIS CONSULTADAS
|
|
if (VariaveisEncontradas && VariaveisEncontradas.length > 0) {
|
|
Encontrou = true;
|
|
for (let i = 0; i < VariaveisEncontradas.length; i++) {
|
|
for (let o = 0; o < VariaveisFrase.length; o++) {
|
|
if (
|
|
VariaveisFrase[o].description ==
|
|
VariaveisEncontradas[i].description
|
|
) {
|
|
VariaveisFrase[o].idalexavariables =
|
|
VariaveisEncontradas[i].idalexavariables;
|
|
VariaveisFrase[o].valuecli = VariaveisEncontradas[i].valuecli;
|
|
}
|
|
}
|
|
}
|
|
//console.log(VariaveisFrase);
|
|
}
|
|
|
|
// ALUNO FALANDO SEUS DADOS QUE SERAO SALVOS NO BANCO
|
|
if (AlunoFalando) {
|
|
AtualizaValoresVariaveis(
|
|
!Encontrou,
|
|
idzoechattimedialog,
|
|
FraseEntrada,
|
|
VariaveisFrase,
|
|
Matricula,
|
|
IDUnidade,
|
|
function (NovoValor) {
|
|
logData('Variável atualizada: ' + NovoValor);
|
|
FraseSubstituida = FraseEntrada;
|
|
callback(FraseSubstituida);
|
|
}
|
|
);
|
|
}
|
|
// ZOE BUSCANDO DADOS DO ALUNO PRA FALAR
|
|
else {
|
|
InsereValoresVariaveisFrase(
|
|
FraseComparada,
|
|
VariaveisFrase,
|
|
function (FraseTrocada) {
|
|
logData('Variável inserida na frase');
|
|
FraseSubstituida = FraseTrocada;
|
|
callback(FraseSubstituida);
|
|
}
|
|
);
|
|
}
|
|
}
|
|
);
|
|
}
|
|
// NAO EXISTEM VARIAVEIS NA FRASE
|
|
else {
|
|
logData('Não existem variáveis na frase');
|
|
FraseSubstituida =
|
|
!AlunoFalando && FraseComparada ? FraseComparada : FraseEntrada;
|
|
callback(FraseSubstituida);
|
|
}
|
|
}
|
|
|
|
function InsereValoresVariaveisFrase(FraseEntrada, VariaveisFrase, callback) {
|
|
let FraseTrocada = FraseEntrada;
|
|
|
|
for (let i = 0; i < VariaveisFrase.length; i++) {
|
|
FraseTrocada = ReplaceAll(
|
|
FraseTrocada,
|
|
['+' + VariaveisFrase[i].description + '+'],
|
|
[VariaveisFrase[i].valuecli],
|
|
5
|
|
);
|
|
}
|
|
|
|
callback(FraseTrocada);
|
|
}
|
|
|
|
function EnviaResposta(
|
|
CriarAudio,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
ExemploResposta,
|
|
Vezes,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
Velocidade,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
VozIngles,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
) {
|
|
logData('Enviar resposta');
|
|
const shell = require('shelljs');
|
|
|
|
mysqlConnection.query(
|
|
'select TTSmode, RMaudio, PythonVersion, extAudio, zoevoiceEn, zoevoicePt, zoevoiceEs from config;',
|
|
function (error, Config, fields) {
|
|
logData('Consulta config realizada');
|
|
const TTSmode = Config[0]['TTSmode'];
|
|
const PythonVersion = Config[0]['PythonVersion'];
|
|
const ExtAudio = Config[0]['extAudio'];
|
|
|
|
const VozZoeEn = experienciaUnilever ? VozesUnilever.En : Config[0]['zoevoiceEn'];
|
|
const VozZoePt = experienciaUnilever ? VozesUnilever.Pt : Config[0]['zoevoicePt'];
|
|
const VozZoeEs = experienciaUnilever ? VozesUnilever.Es : Config[0]['zoevoiceEs'];
|
|
|
|
if (TTSmode == 1) {
|
|
// PICO2WAV
|
|
if (CriarAudio) {
|
|
// CONVERTE A RESPOSTA EM TEXTO PARA AUDIO
|
|
shell.exec(
|
|
`pico2wave --wave=${
|
|
Variables('src_media') +
|
|
'audioZoe2/' +
|
|
NomeArquivo.split('.')[0]
|
|
}.wav \"${Resposta} \"`,
|
|
function (Resultado) {
|
|
// CONVERTE O AUDIO .WAV PARA .MP3
|
|
shell.exec(
|
|
`ffmpeg -i ${Variables('src_media')}audioZoe2/${
|
|
NomeArquivo.split('.')[0]
|
|
}.wav ${Variables('src_media')} audioZoe2/${
|
|
NomeArquivo.split('.')[0]
|
|
}_exit${ExtAudio} -loglevel quiet -stats`,
|
|
function (sucesso) {
|
|
// APAGA O AUDIO .WAV DO SERVIDOR
|
|
shell.exec(
|
|
`rm ${Variables('src_media')}audioZoe2/${
|
|
NomeArquivo.split('.')[0]
|
|
}.wav`
|
|
);
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
} else if (TTSmode == 2) {
|
|
// PYTHON gTTS OP2
|
|
if (CriarAudio) {
|
|
// CONVERTE A RESPOSTA EM TEXTO PARA AUDIO
|
|
shell.exec(
|
|
`${PythonVersion} ${Variables(
|
|
'src_media'
|
|
)}assets/text_to_audio2.py \"${Resposta}\" ${NomeArquivo}`,
|
|
function (Sucesso) {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
RemoverEntrada,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
RemoverEntrada,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
} else if (TTSmode == 3) {
|
|
// WIDEO
|
|
if (CriarAudio) {
|
|
const request = require('request');
|
|
var options = {
|
|
uri: 'https://texttospeechapi.wideo.co/api/wideo-text-to-speech',
|
|
method: 'POST',
|
|
json: {
|
|
data: {
|
|
text: Resposta,
|
|
speed: Velocidade - Vezes * 0.05,
|
|
voice: VozIngles == 1 ? VozZoeEn : VozZoePt,
|
|
},
|
|
},
|
|
};
|
|
request(options, function (error, response, body) {
|
|
if (!error && response.statusCode == 200) {
|
|
let ComandoBaixar = `wget "${
|
|
response['body']['result']['url']
|
|
}" -O ${Variables('src_media')}audioZoe2/${
|
|
NomeArquivo.split('.')[0]
|
|
}_exit.mp3 -q;`;
|
|
shell.exec(ComandoBaixar, function (Sucesso) {
|
|
if (ExtAudio == '.wav') {
|
|
shell.exec(
|
|
`ffmpeg -loglevel panic -i ${Variables(
|
|
'src_media'
|
|
)}audioZoe2/${
|
|
NomeArquivo.split('.')[0]
|
|
}_exit.mp3 ${Variables('src_media')}audioZoe2/${
|
|
NomeArquivo.split('.')[0]
|
|
}_exit.wav`,
|
|
function (Sucesso) {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
});
|
|
}
|
|
});
|
|
} else {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
RemoverEntrada,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
} else if (TTSmode == 4) {
|
|
logData('TTS Amazon Polly');
|
|
// AMAZON POLLY
|
|
const fs = require('fs');
|
|
|
|
// CONVERTE A RESPOSTA EM TEXTO PARA AUDIO
|
|
shell.exec(
|
|
`${PythonVersion} ${Variables(
|
|
'src_media'
|
|
)}assets/polly_service.py \"${Resposta}\" "${Variables(
|
|
'src_media'
|
|
)}audioZoe2/${NomeArquivo}_exit.mp3" "${
|
|
Modo == 0 || !Validou ?
|
|
(IdiomaZoe == "pt-BR" ? VozZoePt :
|
|
IdiomaZoe == "en-US" ? VozZoeEn :
|
|
IdiomaZoe == "es-ES" ? VozZoeEs :
|
|
VozZoeEn) :
|
|
VozIngles == 1 ? VozZoeEn :
|
|
VozIngles == 2 ? VozZoePt :
|
|
VozIngles == 3 ? VozZoeEs :
|
|
VozZoeEn
|
|
}"`,
|
|
function (Sucesso) {
|
|
logData('Texto convertido para audio');
|
|
if (ExtAudio == '.wav') {
|
|
let fileDirectory =
|
|
Variables('src_media') + 'audioZoe2/' + NomeArquivo;
|
|
shell.exec(
|
|
'lame --decode ' +
|
|
'"' +
|
|
fileDirectory +
|
|
'"' +
|
|
'_exit.mp3 ' +
|
|
'"' +
|
|
fileDirectory +
|
|
'"' +
|
|
'_exit.wav',
|
|
function (Sucesso) {
|
|
logData('Convertido wav para mp3');
|
|
fs.chmodSync(fileDirectory + '_exit.wav', 0o777);
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
}
|
|
);
|
|
} else if (TTSmode == 5) {
|
|
// PYTHON gTTS OP1
|
|
if (CriarAudio) {
|
|
// CONVERTE A RESPOSTA EM TEXTO PARA AUDIO
|
|
const textToaudio = spawn('python', [
|
|
Variables('src_media') + 'assets/text_to_audio.py',
|
|
Resposta,
|
|
NomeArquivo,
|
|
]);
|
|
textToaudio.stdout.on('data', function (data) {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
RemoverEntrada,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
});
|
|
} else {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
RemoverEntrada,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
} else if (TTSmode == 6) {
|
|
// WATSON IBM
|
|
const fs = require('fs');
|
|
let respostaFiltered = Resposta.replace('?', 'INT');
|
|
respostaFiltered = respostaFiltered.replace('/', 'BAR');
|
|
if (
|
|
fs.existsSync(
|
|
Variables('src_media') +
|
|
'audioZoe2/' +
|
|
respostaFiltered +
|
|
'_exit.wav'
|
|
)
|
|
) {
|
|
//file exists
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
Resposta,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
} else {
|
|
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
|
|
const { IamAuthenticator } = require('ibm-watson/auth');
|
|
|
|
const textToSpeech = new TextToSpeechV1({
|
|
authenticator: new IamAuthenticator({ apikey: watsonIMBKey }),
|
|
serviceUrl: watsonURLService,
|
|
});
|
|
|
|
const params = {
|
|
text: Resposta,
|
|
voice: VozIngles == 1 ? VozZoeEn : VozZoePt,
|
|
accept: 'audio/wav',
|
|
};
|
|
console.log(
|
|
'request body : ' + params[0] + ',' + params[1] + ',' + params[2]
|
|
);
|
|
textToSpeech
|
|
.synthesize(params)
|
|
.then((response) => {
|
|
const audio = response.result;
|
|
return textToSpeech.repairWavHeaderStream(audio);
|
|
})
|
|
.then((repairedFile) => {
|
|
fs.writeFileSync(
|
|
Variables('src_media') +
|
|
'audioZoe2/' +
|
|
respostaFiltered +
|
|
'_exit.wav',
|
|
repairedFile
|
|
);
|
|
console.log('audio.wav written with a corrected wav header');
|
|
if (ExtAudio == '.mp3') {
|
|
shell.exec(
|
|
'ffmpeg -loglevel panic -i ' +
|
|
Variables('src_media') +
|
|
'audioZoe2/' +
|
|
respostaFiltered +
|
|
'_exit.wav ' +
|
|
Variables('src_media') +
|
|
'audioZoe2/' +
|
|
respostaFiltered +
|
|
'_exit.mp3',
|
|
function (Sucesso) {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
respostaFiltered,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
respostaFiltered,
|
|
Vezes,
|
|
ExemploResposta,
|
|
Resposta,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
);
|
|
}
|
|
})
|
|
.catch((err) => {
|
|
console.log(err);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
function EnviarDados(
|
|
res,
|
|
CriarAudio,
|
|
NomeArquivo,
|
|
Vezes,
|
|
ExemploResposta,
|
|
TextoAudio,
|
|
Final,
|
|
Coerencia,
|
|
Validou,
|
|
ZoeEntendeu,
|
|
Ordem,
|
|
ExtAudio,
|
|
ZoeTalking,
|
|
ProximoZoeTalking,
|
|
Legenda,
|
|
Modo,
|
|
Seq,
|
|
Img
|
|
) {
|
|
logData('Finalizado, enviado response');
|
|
res.send(
|
|
JSON.stringify({
|
|
status: 200,
|
|
url_audio: CriarAudio
|
|
? 'https://myrobotlab.com.br/audioZoe2/' + NomeArquivo + '_exit' + ExtAudio
|
|
: '',
|
|
TextoAudio: TextoAudio,
|
|
Vezes: Vezes,
|
|
ExemploResposta: ExemploResposta,
|
|
Final: Final,
|
|
Coerencia: Coerencia,
|
|
Validou: Validou,
|
|
ZoeEntendeu: ZoeEntendeu,
|
|
Ordem: Ordem,
|
|
Seq: Seq,
|
|
ZoeTalking: ZoeTalking,
|
|
ProximoZoeTalking: ProximoZoeTalking,
|
|
Legenda: Legenda,
|
|
Modo: Modo,
|
|
img: Img,
|
|
})
|
|
);
|
|
// EXCLUI O ARQUIVO DE AUDIO DE ENTRADA
|
|
//const shell = require('shelljs');
|
|
//shell.exec('rm ' + Variables('src_media') + 'audioZoe2/' + NomeArquivo);
|
|
}
|
|
|
|
/*function UploadFIleToS3(NomeArquivo){
|
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
|
if (!err) {
|
|
uploadFileToBucket(data);
|
|
} else {
|
|
console.log(err);
|
|
}
|
|
});
|
|
}*/
|
|
|
|
function EnviaPerguntaMitsuku(Pergunta, SessaoID, callback) {
|
|
// TROCA A PALAVRA ZOE POR MITSUKU
|
|
Pergunta = ReplaceAll(Pergunta, ['Zoe'], ['Mitsuku'], 10);
|
|
// ENVIA A PERGUNTA EM TEXTO PARA MITSUKU
|
|
const querystring = require('querystring');
|
|
const request = require('request');
|
|
var form = {
|
|
input: Pergunta,
|
|
botid: '9fa364f2fe345a10', // ID do bot (CONSTANTE)
|
|
custid: SessaoID, // ID do usuário falando com o bot, ex: b3dfe148ae499f98
|
|
};
|
|
var formData = querystring.stringify(form);
|
|
request(
|
|
{
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
uri: 'https://kakko.pandorabots.com/pandora/talk-xml',
|
|
body: formData,
|
|
method: 'POST',
|
|
},
|
|
function (err, res2, body) {
|
|
var striptags = require('striptags');
|
|
var Resposta = body;
|
|
try {
|
|
Resposta = body.split('<that>')[1].split('</that>')[0];
|
|
} catch (e) {}
|
|
Resposta = decodeURI(Resposta);
|
|
Resposta = striptags(Resposta);
|
|
|
|
RemoverTagsDoTexto(
|
|
Resposta,
|
|
['xgallery.', 'xloadswf2.', 'xloadswf3.', 'xlink.', 'xnslink.'],
|
|
function (NewResposta) {
|
|
if (NewResposta.includes('Human Virus deletion program started'))
|
|
NewResposta = NewResposta.split(
|
|
'Human Virus deletion program started'
|
|
)[0];
|
|
|
|
if (
|
|
NewResposta.includes(
|
|
'This is a list of the games I can play with you'
|
|
)
|
|
)
|
|
NewResposta =
|
|
NewResposta.split('.')[NewResposta.split('.').length - 1];
|
|
|
|
if (
|
|
NewResposta.includes('<img') &&
|
|
NewResposta.includes('/img>')
|
|
)
|
|
NewResposta =
|
|
NewResposta.split('<P')[0] + NewResposta.split('/P>')[1];
|
|
|
|
if (NewResposta.includes('<P') && NewResposta.includes('/P>'))
|
|
NewResposta =
|
|
NewResposta.split('<P')[0] + NewResposta.split('/P>')[1];
|
|
|
|
NewResposta = ReplaceAll(
|
|
NewResposta,
|
|
['Mitsuku', '<br>', '"'],
|
|
['Zoe', ' ', '"'],
|
|
15
|
|
);
|
|
|
|
callback(NewResposta);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
}
|
|
|
|
function EnviaPerguntaGPT(Pergunta, callback) {
|
|
|
|
// Verificar se a pergunta foi feita em inglês
|
|
//if (!isEnglish(Pergunta)) {
|
|
// callback('Sorry, I only understand English');
|
|
// return;
|
|
//}
|
|
|
|
Pergunta = Pergunta.toLowerCase();
|
|
|
|
Pergunta = ReplaceAll(Pergunta, ['Zoe'], ['ChatGPT'], 10);
|
|
const querystring = require('querystring');
|
|
const request = require('request');
|
|
var form = {
|
|
model: 'gpt-3.5-turbo',
|
|
messages: [
|
|
{
|
|
role: 'user',
|
|
content: Pergunta,
|
|
},
|
|
],
|
|
};
|
|
var formData = JSON.stringify(form);
|
|
request(
|
|
{
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Authorization:
|
|
'Bearer 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',
|
|
},
|
|
uri: 'https://api.openai.com/v1/chat/completions',
|
|
body: formData,
|
|
method: 'POST',
|
|
},
|
|
function (err, res2, body) {
|
|
//console.log(body);
|
|
var respostaGPT = JSON.parse(body);
|
|
var Resposta = respostaGPT['choices'][0]['message']['content'];
|
|
Resposta = ReplaceAll(Resposta, ['ChatGPT'], ['Zoe'], 10);
|
|
Resposta = ReplaceAll(Resposta, ['OpenAI'], ['MyRobot'], 10);
|
|
Resposta = ReplaceAll(Resposta, ['GPT-3'], ['Zoe'], 10);
|
|
Resposta = Resposta.replace(/\n/g, ' ');
|
|
console.log('Resposta: ' + Resposta);
|
|
|
|
callback(Resposta);
|
|
}
|
|
);
|
|
}
|
|
|
|
function EnviaPerguntaRosie(Pergunta, callback) {
|
|
Pergunta = ReplaceAll(Pergunta, ['Zoe'], ['Rosie'], 10);
|
|
const querystring = require('querystring');
|
|
const request = require('request');
|
|
var form = {
|
|
botcust2: 'e007f413decb76eb',
|
|
message: Pergunta,
|
|
};
|
|
var formData = querystring.stringify(form);
|
|
request(
|
|
{
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
uri: 'https://pandorabots.com/pandora/talk?botid=b16e613a3e341aa4',
|
|
body: formData,
|
|
method: 'POST',
|
|
},
|
|
function (err, res2, body) {
|
|
var Resposta = body;
|
|
try {
|
|
Resposta = body.split('Rosie:</b> ')[1].split(' <br>')[0];
|
|
} catch (e) {}
|
|
|
|
Resposta = ReplaceAll(Resposta, ['Rosie'], ['Zoe'], 10);
|
|
|
|
//console.log(Resposta);
|
|
|
|
callback(Resposta);
|
|
}
|
|
);
|
|
}
|
|
|
|
function EnviaPerguntaCleverbot(Pergunta, callback) {
|
|
//Pergunta = ReplaceAll(Pergunta, ["Zoe"], ["Rosie"], 10);
|
|
const querystring = require('querystring');
|
|
const request = require('request');
|
|
var form = {
|
|
uc: 'UseOfficialCleverbotAPI',
|
|
in: encodeURI(Pergunta),
|
|
bot: 'c',
|
|
cbsid: 'WXI2AHQ82N',
|
|
xai: 'WXI,405312017,WXHNGDC4RJ1J',
|
|
ns: 99,
|
|
al: '',
|
|
dl: 'en',
|
|
flag: '',
|
|
user: '',
|
|
mode: 1,
|
|
alt: 0,
|
|
reac: '',
|
|
emo: '',
|
|
sou: 'website',
|
|
xed: '',
|
|
t: 5103,
|
|
};
|
|
var formData = querystring.stringify(form);
|
|
request(
|
|
{
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
uri: 'https://www.cleverbot.com/webservicemin?uc=UseOfficialCleverbotAPI&out=I%27m%20Grant.&in=What%20is%20your%20name%3F&bot=c&cbsid=WXI2AHQ82N&xai=WXI,405312017,WXHNGDC4RJ1J&ns=99&al=&dl=en&flag=&user=&mode=1&alt=0&reac=&emo=&sou=website&xed=&t=5103&',
|
|
body: formData,
|
|
method: 'POST',
|
|
},
|
|
function (err, res2, body) {
|
|
var Resposta = body;
|
|
//console.log(body);
|
|
//try { Resposta = body.split("Rosie:</b> ")[1].split(" <br>")[0]; } catch (e) { }
|
|
|
|
//Resposta = ReplaceAll(Resposta, ["Rosie"], ["Zoe"], 10);
|
|
|
|
callback(Resposta);
|
|
}
|
|
);
|
|
}
|
|
|
|
function ExcludeZoeAudios() {}
|
|
|
|
function EnviaPerguntaKuki(Pergunta, SessaoID, callback) {
|
|
Pergunta = ReplaceAll(Pergunta, ['Zoe'], ['Kuki'], 10);
|
|
const querystring = require('querystring');
|
|
const request = require('request');
|
|
var form = {
|
|
input: Pergunta,
|
|
sessionid: SessaoID,
|
|
channel: 7,
|
|
botkey:
|
|
'icH-VVd4uNBhjUid30-xM9QhnvAaVS3wVKA3L8w2mmspQ-hoUB3ZK153sEG3MX-Z8bKchASVLAo~',
|
|
client_name: 'kp17725cfe611',
|
|
};
|
|
var formData = querystring.stringify(form);
|
|
request(
|
|
{
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
uri: 'https://icap.iconiq.ai/talk',
|
|
body: formData,
|
|
method: 'POST',
|
|
},
|
|
function (err, res2, body) {
|
|
var Resposta = JSON.parse(body)['responses'][0];
|
|
//console.log(Resposta);
|
|
|
|
if (Resposta.includes('Image from '))
|
|
Resposta =
|
|
Resposta.split('Image from ')[0] + Resposta.split('</image>')[1];
|
|
|
|
if (Resposta.includes('<image>') && Resposta.includes('</image>'))
|
|
Resposta =
|
|
Resposta.split('<image>')[0] + Resposta.split('</image>')[1];
|
|
|
|
if (Resposta.includes('I can currently play these games:')) {
|
|
Resposta = Resposta.split('I can currently play these games:')[0];
|
|
if (Resposta == '') Resposta = 'I would love to';
|
|
}
|
|
|
|
if (
|
|
Resposta.includes(
|
|
'**What website, app or Discord server are you using to talk to me?'
|
|
)
|
|
)
|
|
Resposta = Resposta.replace(
|
|
'**What website, app or Discord server are you using to talk to me?',
|
|
''
|
|
);
|
|
|
|
if (
|
|
Resposta.includes('("status":"error", "message":"401 unauthorized")')
|
|
)
|
|
Resposta = Resposta.replace(
|
|
'("status":"error", "message":"401 unauthorized")',
|
|
''
|
|
);
|
|
|
|
// I can currently play these games:
|
|
|
|
Resposta = ReplaceAll(
|
|
Resposta,
|
|
['Kuki', 'Mitsuku', '<br>', '"'],
|
|
['Zoe', 'Zoe', ' ', '"'],
|
|
15
|
|
);
|
|
callback(Resposta);
|
|
}
|
|
);
|
|
}
|
|
|
|
function EnviaPerguntaTalkFlow(Pergunta, SessaoID, callback) {
|
|
//Pergunta = ReplaceAll(Pergunta, ['Zoe'], ['Rosie'], 10);
|
|
const request = require('request');
|
|
var form = {
|
|
email: "CONTATO@MYROBOT.COM.BR",
|
|
question: Pergunta,
|
|
client_id: 21
|
|
};
|
|
var formData = JSON.stringify(form);
|
|
request(
|
|
{
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
uri: 'https://panel.walo.us/chat/send_message_api',
|
|
body: formData,
|
|
method: 'POST',
|
|
},
|
|
function (err, res2, body) {
|
|
const resJson = JSON.parse(body);
|
|
var Resposta = resJson.answer;
|
|
|
|
console.log("Respsota TalkFlow: " + Resposta);
|
|
|
|
callback(Resposta);
|
|
}
|
|
);
|
|
}
|
|
|
|
function EnviaPerguntaChatBot(Pergunta, SessaoID, Matricula, callback) {
|
|
mysqlConnection.query(
|
|
`select ChatBot, (select count(1) from users where user = '${Matricula}' and idusertype = 18) as Talkflow from config;`,
|
|
function (error, Config, fields) {
|
|
const ChatBot = Config[0]['ChatBot'];
|
|
const Talkflow = Config[0]['Talkflow'];
|
|
logData("Enviando pergunta para o chatbot");
|
|
if (Talkflow == 1) {
|
|
// talk flow
|
|
logData("Chatbot Talk Flow");
|
|
EnviaPerguntaTalkFlow(Pergunta, SessaoID, function (Resposta) {
|
|
useToken(SessaoID);
|
|
callback(Resposta);
|
|
});
|
|
}
|
|
else {
|
|
if (ChatBot == 1) {
|
|
// MITSUKU
|
|
logData("Chatbot Mitsuko");
|
|
EnviaPerguntaMitsuku(Pergunta, SessaoID, function (Resposta) {
|
|
callback(Resposta);
|
|
});
|
|
} else if (ChatBot == 2) {
|
|
// ROSIE
|
|
logData("Chatbot Rosie");
|
|
EnviaPerguntaRosie(Pergunta, function (Resposta) {
|
|
callback(Resposta);
|
|
});
|
|
} else if (ChatBot == 3) {
|
|
// CLEVERBOT
|
|
logData("Chatbot Cleverbot");
|
|
EnviaPerguntaCleverbot(Pergunta, function (Resposta) {
|
|
callback(Resposta);
|
|
});
|
|
} else if (ChatBot == 4) {
|
|
// KUKI
|
|
logData("Chatbot Kuki");
|
|
EnviaPerguntaKuki(Pergunta, SessaoID, function (Resposta) {
|
|
callback(Resposta);
|
|
});
|
|
} else if (ChatBot == 5) {
|
|
// gpt
|
|
logData("Chatbot ChatGPT");
|
|
EnviaPerguntaGPT(Pergunta, function (Resposta) {
|
|
callback(Resposta);
|
|
});
|
|
} else if (ChatBot == 6) {
|
|
// talk flow
|
|
logData("Chatbot Talk Flow");
|
|
EnviaPerguntaTalkFlow(Pergunta, SessaoID, function (Resposta) {
|
|
callback(Resposta);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
function TrataRespostaChatBot(Resposta, callback) {
|
|
let Tratada = Resposta;
|
|
Tratada = ReplaceAll(Tratada, ['<br>', '"'], [' ', "'"], 15);
|
|
mysqlConnection.query(
|
|
`SELECT tf.* FROM zoetratamentofrases tf inner join config cf on cf.ChatBot = tf.ChatBot;`,
|
|
function (error, Tratamentos, fields) {
|
|
if (Tratamentos && Tratamentos.length > 0) {
|
|
for (let i = 0; i < Tratamentos.length; i++) {
|
|
if (Tratamentos[i]['frase'] == Resposta) {
|
|
Tratada = Tratamentos[i]['trocada'];
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
callback(Tratada);
|
|
}
|
|
);
|
|
}
|
|
|
|
function RemoverTagsDoTexto(Texto, Palavras, callback) {
|
|
let NovoTexto = '';
|
|
for (let p = 0; p < Palavras.length; p++) {
|
|
for (var i = 0; i < Texto.split(Palavras[p]).length; i++) {
|
|
if (i % 2 == 0) NovoTexto += Texto.split(Palavras[p])[i];
|
|
}
|
|
if (NovoTexto != '') Texto = NovoTexto;
|
|
NovoTexto = '';
|
|
}
|
|
callback(Texto);
|
|
}
|
|
|
|
function ReplaceAll(Texto, Palavras, TrocarPor, Vezes) {
|
|
try {
|
|
for (let i = 0; i < Vezes; i++) {
|
|
for (let o = 0; o < Palavras.length; o++) {
|
|
Texto = Texto.replace(Palavras[o], TrocarPor[o]);
|
|
}
|
|
}
|
|
}
|
|
catch (e) {
|
|
|
|
}
|
|
|
|
return Texto;
|
|
}
|
|
|
|
function AtualizaValoresVariaveis(
|
|
ModoInserir,
|
|
idzoechattimedialog,
|
|
FraseEntrada,
|
|
Variaveis,
|
|
Matricula,
|
|
IDUnidade,
|
|
callback
|
|
) {
|
|
// VERIFICA TODAS AS SENTENCAS DESSA INTENCAO
|
|
mysqlConnection.query(
|
|
`select * from zoechattimesentences where idzoechattimedialog = ${idzoechattimedialog};`,
|
|
function (error, ChatTimeSentences, fields) {
|
|
let ArrayPergunta = FraseEntrada.split(' ');
|
|
let UltimoIndexArray = ArrayPergunta.length - 1;
|
|
// REMOVE O \r\n DO FINAL DA ULTIMA PALAVRA
|
|
for (let i = 0; i < ArrayPergunta[UltimoIndexArray].length; i++) {
|
|
let UltimaLeta =
|
|
ArrayPergunta[UltimoIndexArray][
|
|
ArrayPergunta[UltimoIndexArray].length - 1
|
|
];
|
|
if (UltimaLeta == '\r' || UltimaLeta == '\n') {
|
|
ArrayPergunta[UltimoIndexArray] = ArrayPergunta[
|
|
UltimoIndexArray
|
|
].substring(0, ArrayPergunta[UltimoIndexArray].length - 1);
|
|
} else break;
|
|
}
|
|
|
|
// MONTA ARRAY DE PALAVRAS DE TODAS AS SENTENCAS DESSA INTENCAO
|
|
let Sentencas = [];
|
|
for (let o = 0; o < ChatTimeSentences.length; o++) {
|
|
Sentencas.push(ChatTimeSentences[o]['sentence'].split(' '));
|
|
}
|
|
|
|
let NovoValor = '';
|
|
let indexVariavelAtual = 0;
|
|
|
|
//console.log(Sentencas);
|
|
//console.log(ArrayPergunta);
|
|
|
|
// PARA CADA VARIAVEL CONTIDA NA FRASE
|
|
for (let i = 0; i < Variaveis.length; i++) {
|
|
// PARA CADA SENTENCA VERIFICA QUAIS AS PALAVRAS NAO ESTAO PRESENTES NESTA PARA VERIFICAR SE CONDIZ COM A VARIAVEL
|
|
indexVariavelAtual = i;
|
|
for (let o = 0; o < Sentencas.length; o++) {
|
|
// PARA CADA SENTENCA
|
|
for (let p = 0; p < ArrayPergunta.length; p++) {
|
|
// PARA CADA PALAVRA DA FRASE DO USUARIO
|
|
for (let q = 0; q < Sentencas[o].length; q++) {
|
|
// PARA CADA PALAVRA DE CADA SENTENCA
|
|
if (
|
|
Sentencas[o][q].toLowerCase() ==
|
|
ArrayPergunta[p].toLowerCase()
|
|
)
|
|
// VERIFICA SE AS PALAVRAS SAO IGUAIS
|
|
ArrayPergunta[p] = ''; // SE IGUAIS ENTAO REMOVE, MANTENDO SOMENTE AS DIFERENTES NO ARRAY
|
|
}
|
|
}
|
|
}
|
|
|
|
//console.log(ArrayPergunta);
|
|
|
|
// VERIFICAR OS VALORES QUE SAO DIFERENTES DAS PALAVRAS CONTIDAS NAS FRASES, ATRIBUINDO O VALOR DA VARIAVEL COM ESTE
|
|
for (let o = 0; o < ArrayPergunta.length; o++) {
|
|
if (ArrayPergunta[o] != '') {
|
|
if (!Variaveis[i].description.includes('Spell'))
|
|
// SE FOR ALGUMA VARIAVEL DE TEXTO
|
|
NovoValor += (NovoValor != '' ? ' ' : '') + ArrayPergunta[o];
|
|
else {
|
|
// SE FOR ALGUMA VARIAVEL DE SOLETRAGEM
|
|
if (ArrayPergunta[o].length == 1)
|
|
// SE A PALAVRAS TIVER APENAS UMA LETRA
|
|
NovoValor += (NovoValor != '' ? '-' : '') + ArrayPergunta[o];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// ALTERA O VALOR DA VARIAVEL PARA O NOVO VALOR DITO PELO ALUNO
|
|
Variaveis[indexVariavelAtual].valuecli = NovoValor;
|
|
|
|
InserirValorVariavel(
|
|
ModoInserir,
|
|
Variaveis[indexVariavelAtual],
|
|
Matricula,
|
|
IDUnidade,
|
|
function (Sucesso) {
|
|
callback(NovoValor);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
}
|
|
|
|
function InserirValorVariavel(
|
|
Inserir,
|
|
Variavel,
|
|
Matricula,
|
|
IDUnidade,
|
|
callback
|
|
) {
|
|
//console.log(Variavel);
|
|
Variavel.valuecli = ReplaceAll(Variavel.valuecli, "'", '"', 10);
|
|
let sqlChangeVariable = ``;
|
|
if (Inserir == true) {
|
|
sqlChangeVariable = `INSERT INTO alexauservariables (idalexavariables, valuecli, idusers, idunits)
|
|
VALUES ((SELECT idalexavariables FROM alexavariables WHERE description = '${Variavel.description}'), '${Variavel.valuecli}', ${Matricula}, ${IDUnidade});`;
|
|
} else {
|
|
sqlChangeVariable = `UPDATE alexauservariables SET valuecli = '${Variavel.valuecli}' WHERE idalexavariables = ${Variavel.idalexavariables} AND idusers = ${Matricula} AND idunits = ${IDUnidade};`;
|
|
}
|
|
//console.log(sqlChangeVariable);
|
|
mysqlConnection.query(sqlChangeVariable, function (error, results, fields) {
|
|
let Sucesso = true;
|
|
if (error) {
|
|
Sucesso = false;
|
|
console.log(
|
|
"Erro ao definir valor da variável '" + Variavel.description + "'"
|
|
);
|
|
console.log(error);
|
|
console.log(sqlChangeVariable);
|
|
}
|
|
callback(Sucesso);
|
|
});
|
|
}
|
|
|
|
function ModoConfiguracao(Pergunta, NomeArquivo, res, Matricula, IDUnidade) {
|
|
let Resposta = '';
|
|
try {
|
|
if (Pergunta.toLowerCase().includes(FraseMudarVariavel)) {
|
|
// ALTERAR VALOR DA VARIAVEL - FRASE EXEMPLO: change my name to Diego
|
|
let Variavel = Pergunta.split(FraseMudarVariavel)[1].split(' ')[0]; // change my NAME to diego
|
|
let NovoValor = Pergunta.split(Variavel + ' to ')[1]; // change my name to DIEGO
|
|
//NovoValor = NovoValor.substring(0, NovoValor.length - 1);
|
|
let sqlSearchVariable = `SELECT av.idalexavariables, av.description, au.valuecli FROM alexauservariables au INNER JOIN alexavariables av ON av.idalexavariables = au.idalexavariables WHERE au.idusers = ${Matricula} AND au.idunits = ${IDUnidade} AND av.description = '${Variavel}';`;
|
|
mysqlConnection.query(
|
|
sqlSearchVariable,
|
|
function (error, results, fields) {
|
|
let FormVariavel = {
|
|
idalexavariables: 0,
|
|
description: Variavel,
|
|
valuecli: NovoValor,
|
|
};
|
|
let ModoInserir = false;
|
|
if (results.length == 0) {
|
|
ModoInserir = false;
|
|
} else {
|
|
FormVariavel.idalexavariables = results[0].idalexavariables;
|
|
FormVariavel.description = results[0].description;
|
|
FormVariavel.valuecli = NovoValor;
|
|
}
|
|
|
|
InserirValorVariavel(
|
|
ModoInserir,
|
|
FormVariavel,
|
|
Matricula,
|
|
IDUnidade,
|
|
function (Sucesso) {
|
|
if (Sucesso)
|
|
// CONSEGUIU DEFINIR A VARIAVEL COM O NOVO VALOR
|
|
Resposta =
|
|
'Your ' + Variavel + ' was changed to ' + NovoValor;
|
|
// ERRO AO DEFINIR NOVO VALOR PARA VARIAVEL
|
|
else Resposta = 'Fail to define your ' + Variavel;
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
FraseExemploConfig,
|
|
0,
|
|
1,
|
|
Sucesso ? 100 : 0,
|
|
Sucesso ? 1 : 0,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
0,
|
|
2,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
} else if (Pergunta.toLowerCase().includes(FraseDizerVariavel)) {
|
|
// FALAR VALOR DA VARIAVEL - FRASE EXEMPLO: say my name
|
|
let Variavel = Pergunta.split(FraseDizerVariavel)[1]; // say my NAME
|
|
//Variavel = Variavel.substring(0, Variavel.length - 1);
|
|
ConsultarValorVariavel(
|
|
Variavel,
|
|
Matricula,
|
|
IDUnidade,
|
|
function (valuecli) {
|
|
if (valuecli != '')
|
|
// ENCONTROU VALOR PARA ESSA VARIAVEL
|
|
Resposta = 'Your ' + Variavel + ' is ' + valuecli;
|
|
// NAO ENCONTROU VALOR PARA ESSA VARIAVEL
|
|
else
|
|
Resposta =
|
|
'I yet not know your ' +
|
|
Variavel +
|
|
'. Say change my ' +
|
|
Variavel +
|
|
' to your ' +
|
|
Variavel +
|
|
' to insert it.';
|
|
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
FraseExemploConfig,
|
|
0,
|
|
1,
|
|
100,
|
|
1,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
0,
|
|
2,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
);
|
|
} else {
|
|
// COMANDO DESCONHECIDO
|
|
Resposta = EscolheFraseNaoEntendeu();
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
FraseExemploConfig,
|
|
0,
|
|
1,
|
|
0,
|
|
0,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
0,
|
|
2,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
} catch (e) {
|
|
// HOUVE ALGUM ERRO DURANTE O PROCESSO OU FRASE INCORRETA
|
|
Resposta = EscolheFraseNaoEntendeu();
|
|
EnviaResposta(
|
|
true,
|
|
Resposta,
|
|
NomeArquivo,
|
|
res,
|
|
FraseExemploConfig,
|
|
0,
|
|
1,
|
|
0,
|
|
0,
|
|
VelocidadePadrao,
|
|
Pergunta,
|
|
0,
|
|
1,
|
|
0,
|
|
1,
|
|
0,
|
|
2,
|
|
0,
|
|
''
|
|
);
|
|
}
|
|
}
|
|
|
|
function ConsultarValorVariavel(Variavel, Matricula, IDUnidade, callback) {
|
|
let sqlShowVariable = `SELECT au.valuecli FROM alexauservariables au INNER JOIN alexavariables av ON av.idalexavariables = au.idalexavariables WHERE au.idusers = ${Matricula} AND au.idunits = ${IDUnidade} AND av.description = '${Variavel}';`;
|
|
//console.log(sqlShowVariable);
|
|
mysqlConnection.query(sqlShowVariable, function (error, results, fields) {
|
|
let ValorVariavel = '';
|
|
if (results.length > 0) ValorVariavel = results[0]['valuecli'];
|
|
else ValorVariavel = '';
|
|
callback(ValorVariavel);
|
|
});
|
|
}
|
|
|
|
function LimparCaracteres(Texto) {
|
|
return Texto.replace(/[^a-zA-Z\d]/g, '').toLowerCase();
|
|
}
|
|
|
|
// #endregion
|
|
|
|
return router;
|
|
};
|
|
|
|
module.exports = routes;
|