-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.js
102 lines (88 loc) · 2.6 KB
/
web.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// web.js
// a quick node.js server which serves up handwriting
// (c) 2013 Amit Mizrahi
var ejs = require('ejs');
var express = require('express');
var fs = require('fs');
var http = require('http');
var app = express();
var assert = require("assert"),
brain = require("brain"),
bodyParser = require('body-parser'),
multer = require('multer');
//Neural network definition
var net = new brain.NeuralNetwork({
hiddenLayers: [5, 5],
momentum:0.7
});
var _error=0;
var _iterations=0;
app.engine('html', ejs.renderFile);
app.set('views', __dirname);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser({limit:'50mb'}));
app.use(multer({ dest: './uploads/'}))
app.get('/', function (req, res) {
res.render('app.html');
});
app.post('/train', function(req, res){
var trainData = req.body.entrenamiento;
var epochs = req.body.epochs;
_error = 0;
_iterations = 0;
net.train(trainData, {
iterations:epochs,
callbackPeriod:1,
callback:function(m){
console.log(m);
_error = m.error;
_iterations = m.iterations;
res.end('OK');
}
});
});
app.get('/checkNet', function(req, res){
res.end(JSON.stringify({'error':_error, 'iterations':_iterations}));
});
app.get('/getNet', function(req, res){
res.attachment('neural_net.json');
res.end(JSON.stringify(net.toJSON(), null, 2), 'utf8');
});
app.post('/test', function(req, res){
var prueba = req.body.prueba;
var result = net.run(prueba);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(result));
});
app.get('/random', function(req, res) {
var fileNumber = Math.round(Math.random()*14) + 1;
fs.readFile('/images/'+fileNumber+'.png', function(data) {
res.contentType('image/png');
res.end('/images/'+fileNumber+'.png', 'binary');
});
});
app.get('/image/:fileNumber', function(req, res) {
fileNumber = req.param('fileNumber');
fs.readFile('/images/'+fileNumber+'.png', function(data) {
res.contentType('image/png');
res.end('/images/'+fileNumber+'.png', 'binary');
});
});
app.post('/file-upload', function(req, res, next) {
var neural_network;
// First I want to read the file
fs.readFile(req.files.jsonFile.path, function read(err, data) {
if (err) {
throw err;
}
//neural_network = data;
if (Buffer.isBuffer( data)){
neural_network = data.toString('utf8');
net.fromJSON(JSON.parse(neural_network));
res.end(JSON.stringify({'status':'success','message':'Red interpretada.'}));
}else{
res.end(JSON.stringify({'status':'error','message':'Archivo de formato no permitido.'}));
}
});
});
app.listen(3000)