2021-02-08 17:39:09 +01:00
|
|
|
import { log } from '../log';
|
2020-11-18 14:26:28 +01:00
|
|
|
import * as tf from '../../dist/tfjs.esm.js';
|
2021-02-13 15:16:41 +01:00
|
|
|
import * as profile from '../profile';
|
2020-11-13 22:13:35 +01:00
|
|
|
|
|
|
|
// based on https://github.com/sirius-ai/MobileFaceNet_TF
|
|
|
|
// model converted from https://github.com/sirius-ai/MobileFaceNet_TF/files/3551493/FaceMobileNet192_train_false.zip
|
|
|
|
|
2021-02-08 18:47:38 +01:00
|
|
|
let model;
|
2020-11-13 22:13:35 +01:00
|
|
|
|
2021-02-08 17:39:09 +01:00
|
|
|
export async function load(config) {
|
2021-02-08 18:47:38 +01:00
|
|
|
if (!model) {
|
|
|
|
model = await tf.loadGraphModel(config.face.embedding.modelPath);
|
2020-12-08 16:50:26 +01:00
|
|
|
log(`load model: ${config.face.embedding.modelPath.match(/\/(.*)\./)[1]}`);
|
2020-11-13 22:13:35 +01:00
|
|
|
}
|
2021-02-08 18:47:38 +01:00
|
|
|
return model;
|
2020-11-13 22:13:35 +01:00
|
|
|
}
|
|
|
|
|
2021-02-08 17:39:09 +01:00
|
|
|
export function simmilarity(embedding1, embedding2) {
|
2020-11-13 22:13:35 +01:00
|
|
|
if (embedding1?.length !== embedding2?.length) return 0;
|
2020-11-23 14:40:17 +01:00
|
|
|
// general minkowski distance
|
|
|
|
// euclidean distance is limited case where order is 2
|
|
|
|
const order = 2;
|
|
|
|
const distance = 10.0 * ((embedding1.map((val, i) => (val - embedding2[i])).reduce((dist, diff) => dist + (diff ** order), 0) ** (1 / order)));
|
|
|
|
return (Math.trunc(1000 * (1 - distance)) / 1000);
|
2020-11-13 22:13:35 +01:00
|
|
|
}
|
|
|
|
|
2021-02-08 17:39:09 +01:00
|
|
|
export async function predict(image, config) {
|
2021-02-08 18:47:38 +01:00
|
|
|
if (!model) return null;
|
2020-11-13 22:13:35 +01:00
|
|
|
return new Promise(async (resolve) => {
|
|
|
|
const resize = tf.image.resizeBilinear(image, [config.face.embedding.inputSize, config.face.embedding.inputSize], false);
|
|
|
|
// const normalize = tf.tidy(() => resize.div(127.5).sub(0.5)); // this is -0.5...0.5 ???
|
2021-02-08 18:47:38 +01:00
|
|
|
let data: Array<[]> = [];
|
2020-11-13 22:13:35 +01:00
|
|
|
if (config.face.embedding.enabled) {
|
|
|
|
if (!config.profile) {
|
2021-02-08 18:47:38 +01:00
|
|
|
const embeddingT = await model.predict({ img_inputs: resize });
|
2020-11-13 22:13:35 +01:00
|
|
|
data = [...embeddingT.dataSync()]; // convert object array to standard array
|
|
|
|
tf.dispose(embeddingT);
|
|
|
|
} else {
|
2021-02-08 18:47:38 +01:00
|
|
|
const profileData = await tf.profile(() => model.predict({ img_inputs: resize }));
|
2020-11-13 22:13:35 +01:00
|
|
|
data = [...profileData.result.dataSync()];
|
|
|
|
profileData.result.dispose();
|
|
|
|
profile.run('emotion', profileData);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
resize.dispose();
|
|
|
|
// normalize.dispose();
|
|
|
|
resolve(data);
|
|
|
|
});
|
|
|
|
}
|