-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEggPredictionController.js
53 lines (40 loc) · 2.04 KB
/
EggPredictionController.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
const fs = require('fs');
const Path = require('path');
const tf = require('@tensorflow/tfjs-node');
const sharp = require('sharp');
const modelLocation = Path.join(__dirname,"/model/tfjs_model");
const imgSaveLocation = Path.join(__dirname, '/uploaded-img');
const EggPredictionController = {
async predict (request, h) {
try {
const data = request.payload.image; // Data unggahan file dari request
if (!data || !data.path) {
return h.response('File tidak ditemukan').code(400);
}
const filePath = data.path;
const imgBuffer = await sharp(filePath).resize(224,224).raw().toBuffer();
const uint8Array = new Uint8Array(imgBuffer);
const normalizedArray = Array.from(uint8Array).map(value => value / 255);
const tensorGambar = tf.tensor(normalizedArray, [224, 224, 3]);
const model_json = Path.join(modelLocation, "/model.json");
const model = await tf.loadGraphModel(`file://${model_json}`);
const className = ['Pertengahan', 'Tahap Akhir', 'Tahap Awal', 'Telur Mati'];
try {
const hasilPrediksi = model.predict(tensorGambar.expandDims(0)).squeeze().arraySync();
const totalProbabilitas = hasilPrediksi.reduce((total, probabilitas) => total + probabilitas, 0);
const prediksi = hasilPrediksi.map((probabilitas, index) => ({
kelas: className[index],
probabilitas: (probabilitas / totalProbabilitas) * 100 // Menghitung persentase probabilitas
}));
return h.response({result : prediksi});
// handling save image-nya disini
} catch (error) {
console.error('Terjadi kesalahan dalam proses prediksi:', error);
}
} catch (error) {
console.error(error);
return h.response('Terjadi kesalahan dalam pemrosesan file').code(500);
}
}
}
module.exports = EggPredictionController;