This repository has been archived by the owner on Dec 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.js
60 lines (47 loc) · 1.85 KB
/
app.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
const canvas = require('canvas');
require('@tensorflow/tfjs-node'); // Load before @teachablemachine/image
const tmImage = require('@teachablemachine/image')
const express = require('express');
const app = express();
app.use(require('body-parser').raw({ type: 'image/png', limit: '3MB' }));
addEndpoint("test", 'https://teachablemachine.withgoogle.com/models/yourmodel/'); //You can add as many endpoints as you like
const JSDOM = require('jsdom').JSDOM;
global.window = new JSDOM(`<body><script>document.body.appendChild(document.createElement("hr"));</script></body>`).window;
global.document = window.document;
global.fetch = require('node-fetch');
app.listen(3000, () => {
console.log("Server running on port 3000");
});
async function addEndpoint(name, URL){
let model;
const modelURL = URL + 'model.json';
const metadataURL = URL + 'metadata.json';
model = await tmImage.load(modelURL, metadataURL);
app.post('/' + name, (req, res, next) => {
getPrediction(model, _arrayBufferToBase64(req.body), (output) => {
res.send(output);
});
});
}
async function getPrediction(model, data, fu) {
const can = canvas.createCanvas(64, 64);
const ctx = can.getContext('2d');
const img = new canvas.Image();
img.onload = async () => {
ctx.drawImage(img, 0, 0, 64, 64);
const prediction = await model.predict(can);
console.log(prediction);
fu(prediction);
}
img.onerror = err => { throw err; }
img.src = "data:image/png;base64," + data;
}
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}