2022-07-07 14:06:37 +02:00
|
|
|
import * as fs from 'node:fs';
|
|
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
import { dirname } from 'node:path';
|
|
|
|
import * as nsfw from 'nsfwjs';
|
2022-07-12 03:38:57 +02:00
|
|
|
import si from 'systeminformation';
|
2022-07-07 14:06:37 +02:00
|
|
|
|
|
|
|
const _filename = fileURLToPath(import.meta.url);
|
|
|
|
const _dirname = dirname(_filename);
|
|
|
|
|
2022-07-12 03:38:57 +02:00
|
|
|
const REQUIRED_CPU_FLAGS = ['avx2', 'fma'];
|
|
|
|
let isSupportedCpu: undefined | boolean = undefined;
|
|
|
|
|
2022-07-07 14:06:37 +02:00
|
|
|
let model: nsfw.NSFWJS;
|
|
|
|
|
|
|
|
export async function detectSensitive(path: string): Promise<nsfw.predictionType[] | null> {
|
|
|
|
try {
|
2022-07-12 03:38:57 +02:00
|
|
|
if (isSupportedCpu === undefined) {
|
|
|
|
const cpuFlags = await getCpuFlags();
|
|
|
|
isSupportedCpu = REQUIRED_CPU_FLAGS.every(required => cpuFlags.includes(required));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isSupportedCpu) {
|
|
|
|
console.error('This CPU cannot use TensorFlow.');
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const tf = await import('@tensorflow/tfjs-node');
|
|
|
|
|
2022-07-07 14:06:37 +02:00
|
|
|
if (model == null) model = await nsfw.load(`file://${_dirname}/../../nsfw-model/`, { size: 299 });
|
|
|
|
|
|
|
|
const buffer = await fs.promises.readFile(path);
|
2022-07-12 03:38:57 +02:00
|
|
|
const image = await tf.node.decodeImage(buffer, 3) as any;
|
2022-07-07 14:06:37 +02:00
|
|
|
try {
|
|
|
|
const predictions = await model.classify(image);
|
|
|
|
return predictions;
|
|
|
|
} finally {
|
|
|
|
image.dispose();
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
2022-07-12 03:38:57 +02:00
|
|
|
|
|
|
|
async function getCpuFlags(): Promise<string[]> {
|
|
|
|
const str = await si.cpuFlags();
|
|
|
|
return str.split(/\s+/);
|
|
|
|
}
|