-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsonny.js
69 lines (63 loc) · 1.9 KB
/
sonny.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// ESTA É A PRIMEIRA VERSÃO DE SONNY, USE À VONTADE, PORÉM PARA MELHOR EXPERIÊNCIA UTILIZE
// testSonny.js e bootSonny.js PARA APRENDER E RODAR RESPECTIVAMENTE.
// Documentação do brain.js: https://github.com/BrainJS/brain.js#brainjs
const fs = require('fs')
const readline = require('readline')
const brain = require('brain.js')
const net = new brain.recurrent.LSTM()
let array
// teste de performance/tempo de aprendizado
let initTime = Date.now();
// configuração readline
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// verifica se o json de treinamento está preenchido
fs.readFile('learned.json', (err, data) => {
if (err) return console.log(err)
if (data.toString() === '') {
console.log('Sonny será treinado agora!')
train();
} else {
net.fromJSON(JSON.parse(data.toString()))
boot();
}
})
// realiza o treinamento
const train = () => {
console.log('treinando sonny...')
fs.readFile('intents.json', (err, data) => {
array = data.toString()
let jsonFile = JSON.parse(array)
let inOuts = []
jsonFile.intents.forEach(element => {
// tempo de treino 2 horas ou mais
if (element.tag == 'saudacoes') {
for (let i = 0; i < element.input.length; i++) {
inOuts.push({
input: element.input[i],
output: element.output[i]
})
}
}
});
// console.log(inOuts)
net.train(inOuts, {
log: true,
});
fs.writeFileSync('learned.json', JSON.stringify(net.toJSON()), (err, result) => {
if (err) return console.log(err)
})
console.log('Treinamento finalizado')
console.log("Sonny foi treinado com 20000 iterações em: ", Date.now() - initTime, ' milisegundos')
boot();
})
}
// inicia o bot caso já tenha sido treinado
const boot = () => {
rl.question('Me: ', (q) => {
console.log(`Sonny: ${net.run(q)}`)
boot();
})
}