human/src/face/antispoof.ts

45 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-10-13 16:56:56 +02:00
/**
* Anti-spoofing model implementation
*/
2022-01-17 17:03:21 +01:00
import { log, now } from '../util/util';
2021-10-13 16:56:56 +02:00
import type { Config } from '../config';
import type { GraphModel, Tensor } from '../tfjs/types';
import * as tf from '../../dist/tfjs.esm.js';
2022-01-16 15:49:55 +01:00
import { loadModel } from '../tfjs/load';
2021-10-13 16:56:56 +02:00
import { env } from '../util/env';
let model: GraphModel | null;
const cached: Array<number> = [];
let skipped = Number.MAX_SAFE_INTEGER;
let lastCount = 0;
2021-10-23 15:38:52 +02:00
let lastTime = 0;
2021-10-13 16:56:56 +02:00
export async function load(config: Config): Promise<GraphModel> {
if (env.initial) model = null;
2022-01-17 17:03:21 +01:00
if (!model) model = await loadModel(config.face.antispoof?.modelPath);
else if (config.debug) log('cached model:', model['modelUrl']);
2021-10-13 16:56:56 +02:00
return model;
}
2021-11-17 22:50:21 +01:00
export async function predict(image: Tensor, config: Config, idx: number, count: number): Promise<number> {
2021-11-13 18:23:32 +01:00
if (!model) return 0;
2021-10-23 15:38:52 +02:00
const skipTime = (config.face.antispoof?.skipTime || 0) > (now() - lastTime);
const skipFrame = skipped < (config.face.antispoof?.skipFrames || 0);
if (config.skipAllowed && skipTime && skipFrame && (lastCount === count) && cached[idx]) {
2021-10-13 16:56:56 +02:00
skipped++;
return cached[idx];
}
skipped = 0;
return new Promise(async (resolve) => {
const resize = tf.image.resizeBilinear(image, [model?.inputs[0].shape ? model.inputs[0].shape[2] : 0, model?.inputs[0].shape ? model.inputs[0].shape[1] : 0], false);
2021-11-02 16:07:11 +01:00
const res = model?.execute(resize) as Tensor;
2021-10-13 16:56:56 +02:00
const num = (await res.data())[0];
cached[idx] = Math.round(100 * num) / 100;
lastCount = count;
2021-10-23 15:38:52 +02:00
lastTime = now();
2021-10-13 16:56:56 +02:00
tf.dispose([resize, res]);
resolve(cached[idx]);
});
}