近日,我偶然在Github发现了一个鉴定不雅内容的 js 库 NSFW JS,出于好奇,于是就研究了一下,并且写了一个demo。下面就跟大家分享一下。

首先,NSFW JS 给一张图片鉴定的结果可能会得到如下 5 个分类结果。

  1. 绘画(Drawing)——无害的艺术,或艺术绘画;
  2. 变态(Hentai)——色情艺术,不适合大多数工作环境;
  3. 中立(Neutral)——一般,无害的内容;
  4. 色情(Porn)——不雅的内容和行为,通常涉及生殖器;
  5. 性感(Sexy)——不合时宜的挑衅内容。

最终结果输出一个数组,每个分类都会输出一个概率,按概率从高到低排,所有分类的概率总和是 1。当年实测的输出长这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[
{
"className": "Sexy",
"probability": 0.35769057273864746
},
{
"className": "Neutral",
"probability": 0.3514401912689209
},
{
"className": "Porn",
"probability": 0.2888406813144684
},
{
"className": "Hentai",
"probability": 0.0012577027082443237
},
{
"className": "Drawing",
"probability": 0.0007708172197453678
}
]

安装

NSFW JS 由 TensorFlow.js 驱动,装库的时候要把这两个一起装上:

1
2
3
4
5
npm i @tensorflow/tfjs
npm i nsfwjs
// 或
yarn add @tensorflow/tfjs
yarn add nsfwjs

依赖版本 nsfwjs 2.4.2 + @tensorflow/tfjs 3.21.0

加载模型

模型文件可以在 nsfw_model 的 release 页面下载。我下的是 1.1.0 版的 nsfw_mobilenet_v2_140_224.zip ,解压后 web_model/ 目录里是一个 model.json 加 6 个 4MB 大小的分片(第 6 片 3.4MB),这种分片形式主要是为了方便浏览器缓存。因为我在 vue 项目中使用,所以把它们放在 /public/model/ 文件夹中:

1
2
3
4
5
6
7
8
public/model/
├── model.json # 网络结构 + 权重清单,134KB
├── group1-shard1of6.bin # 4MB
├── group1-shard2of6.bin # 4MB
├── group1-shard3of6.bin # 4MB
├── group1-shard4of6.bin # 4MB
├── group1-shard5of6.bin # 4MB
└── group1-shard6of6.bin # 3.4MB

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
// 导入模块
import * as nsfwjs from 'nsfwjs'

// 载入模型,路径指向放 model.json 的目录
const model = await nsfwjs.load('/model/', {
size: 224,
type: 'graph'
})

// 鉴定图片
const img = document.getElementById('img')
const predictions = await model.classify(img)
console.log('Predictions: ', predictions)

有三个地方要特别注意:

  • load() 必须把模型路径传进去,不然走的是 CDN;
  • type: 'graph' 是最容易栽的坑。nsfw_model 1.1.0 导出的模型是 TensorFlow 1.x 的 GraphDef 格式,要用 loadGraphModel 加载,不写这个参数会报 layer: Improper config format。官方仓库 demo 里的另一套模型是 Keras 格式,则不需要传这个参数,模型格式不同,加载方式就不同;
  • size: 224 和模型输入一致,不传也是这个默认值,一般不用动。

顺带一提,nsfwjs 2.4.2 的 TypeScript 类型定义里没声明 type 参数,写 TS 的话要 as any 绕一下,运行时是支持的。

在 Vite 里跑起来的坑

页面直接白屏,控制台报 Cannot read properties of undefined (reading 'listenerCount') 。

原因是 nsfwjs 的依赖链里带着 gif-encoder → readable-stream,这些包会引用 Node 的 events 、 buffer 内置模块。webpack 会自动用 polyfill 顶上,Vite 默认却是把 Node 内置模块外部化,浏览器里自然就炸了。解决办法是装个 vite-plugin-node-polyfills:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// vite.config.ts
import {
nodePolyfills
} from 'vite-plugin-node-polyfills'

export default defineConfig({
plugins: [
vue(),
nodePolyfills({
include: ['events', 'buffer', 'stream', 'util', 'zlib'],
globals: {
Buffer: true,
process: true
},
}),
],
})

识别效果

打开页面,模型加载完成后就可以上传图片鉴定了:

demo首页

特意选了一张水彩风景画来测,虽然笔触有点抽象,但模型判定得很稳:Neutral 71.48%、Drawing 15.70%,色情相关的四舍五入约等于零:

鉴定结果

最后,这里附上我写的demo,传送门