-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodeModel.js
More file actions
67 lines (56 loc) · 2.43 KB
/
nodeModel.js
File metadata and controls
67 lines (56 loc) · 2.43 KB
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
const functions = require("firebase-functions");
const tf = require('@tensorflow/tfjs');
const sharp = require('sharp');
exports.predict = functions
.runWith({ timeoutSeconds: 300, memory: '2GB' }) // Increase timeout and memory allocation
.https.onCall(async (data, context) => {
try {
const photo = data.input;
console.log("Received input: ", photo);
// Decode base64 encoded image string to a TensorFlow tensor
const imageTensor = await decodeBase64ToTensor(photo);
console.log("Image tensor shape: ", imageTensor.shape);
// Load the model
const modelUrl = "https://firebasestorage.googleapis.com/v0/b/pocketprotect-cc462.appspot.com/o/skincancer.json?alt=media&token=fd378918-7503-40c9-8aee-33bc9d61337d";
const model = await tf.loadLayersModel(modelUrl);
console.log("Model loaded successfully");
// Preprocess the image tensor as necessary by your model
const preprocessedImageTensor = preprocessImage(imageTensor);
// Make prediction
const prediction = await predict(model, preprocessedImageTensor);
console.log("Prediction result: ", prediction);
// Return prediction result
return { prediction };
} catch (error) {
console.error("Error in predict function:", error);
return { error: error.message };
}
});
async function decodeBase64ToTensor(base64String) {
try {
const buffer = Buffer.from(base64String, 'base64');
const { data, info } = await sharp(buffer)
.resize(224, 224)
.raw()
.toBuffer({ resolveWithObject: true });
const { width, height, channels } = info;
if (width !== 224 || height !== 224 || channels !== 3) {
throw new Error('Image is not the correct size or number of channels.');
}
const imageTensor = tf.tensor3d(new Uint8Array(data), [height, width, channels]);
return imageTensor;
} catch (error) {
console.error("Error in decodeBase64ToTensor function:", error);
throw error;
}
}
function preprocessImage(imageTensor) {
try {
// Normalize the image tensor to have values in [0, 1] and add batch dimension
const normalizedTensor = imageTensor.div(tf.scalar(255.0)).expandDims(0);
return normalizedTensor;
} catch (error) {
console.error("Error in preprocessImage function:", error);
throw error;
}
}