|
const io = require('socket.io-client'); |
|
const tf = require('@tensorflow/tfjs-node'); |
|
|
|
|
|
const socket = io('https://box.km.mk/socket.io'); |
|
socket.emit("user joined", "AITrainer", "green") |
|
|
|
let trainingData = []; |
|
let labels = []; |
|
|
|
|
|
socket.on('data', (data) => { |
|
console.log('Received message:', data); |
|
processMessage(data); |
|
}); |
|
|
|
|
|
function processMessage(message) { |
|
|
|
if (message.text && message.label) { |
|
trainingData.push(message.text); |
|
labels.push(message.label); |
|
console.log('Added to training data:', message.text); |
|
|
|
|
|
if (trainingData.length >= 10) { |
|
trainAI(); |
|
} |
|
} |
|
} |
|
|
|
|
|
async function trainAI() { |
|
console.log('Training AI with collected data...'); |
|
|
|
|
|
const xs = tf.tensor2d(trainingData.map(text => text.split('').map(char => char.charCodeAt(0))), [trainingData.length, trainingData[0].length]); |
|
const ys = tf.tensor2d(labels.map(label => label === 'positive' ? [1] : [0]), [labels.length, 1]); |
|
|
|
|
|
const model = tf.sequential(); |
|
model.add(tf.layers.dense({ units: 5, activation: 'relu', inputShape: [trainingData[0].length] })); |
|
model.add(tf.layers.dense({ units: 1, activation: 'sigmoid' })); |
|
|
|
model.compile({ optimizer: 'adam', loss: 'binaryCrossentropy', metrics: ['accuracy'] }); |
|
|
|
|
|
await model.fit(xs, ys, { epochs: 10 }); |
|
|
|
console.log('Training complete.'); |
|
|
|
|
|
trainingData = []; |
|
labels = []; |
|
} |
|
|
|
|
|
socket.on('connect_error', (err) => { |
|
console.error('Connection error:', err); |
|
}); |
|
|
|
|
|
process.on('SIGINT', () => { |
|
console.log("Shutting down gracefully..."); |
|
socket.disconnect(); |
|
process.exit(); |
|
}); |
|
|
|
console.log("Listening for messages..."); |
|
|
|
|
|
setInterval(() => {}, 1000); |
|
|