Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

nsfwjs

> 编程语言
Open source

NSFW detection on the client-side via TensorFlow.js

8.9K stars0 likes3 views
WebsiteGitHub

About

NSFW detection on the client-side via TensorFlow.js

Client-side indecent content checking

A simple JavaScript library to help you quickly identify unseemly images; all in the client's browser. NSFWJS isn't perfect, but it's pretty accurate (~90% with small and ~93% with midsized model)... and it's getting more accurate all the time.

Why would this be useful? Check out the announcement blog post.

NOTE

If you're trying to access the Cloudfront hosted model and are running into an error, it's likely due to the fact that the model has been moved to a new location. Please take a look at our Host your own model section. We will be returning the model after some hotlinkers have been dealt with.

Table of Contents

  • QUICK: How to use the module
    • Selective model bundles (tree-shaking)
  • Library API
    • load the model
    • Caching
    • classify an image
    • dispose a loaded model
  • Production
  • Backend selection
    • WASM backend (optional)
    • WebGPU backend (optional)
    • Node.js backend
  • Install
    • Host your own model
  • Run the Examples
    • Tensorflow.js in the browser
    • Browserify
    • React Native
    • Node JS App
    • NSFW Filter
  • Learn TensorFlow.js
  • More!
    • Open Source
    • Need the experts? Hire Infinite Red for your next project
  • Contributors

The library categorizes image probabilities in the following 5 classes:

  • Drawing - safe for work drawings (including anime)
  • Hentai - hentai and pornographic drawings
  • Neutral - safe for work neutral images
  • Porn - pornographic images, sexual acts
  • Sexy - sexually explicit images, not pornography

The demo is a continuous deployment source - Give it a go: http://nsfwjs.com

QUICK: How to use the module

javascript
import * as nsfwjs from "nsfwjs";

const img = document.getElementById("img");

// If you want to host models on your own or use different model from the ones available, see the section "Host your own model".
const model = await nsfwjs.load();

// Classify the image
const predictions = await model.classify(img);
console.log("Predictions: ", predictions);

Selective model bundles (tree-shaking)

nsfwjs keeps the default behavior and includes built-in model definitions. For selective bundling, import from nsfwjs/core and pass only the models you want in modelDefinitions.

javascript
import { load } from "nsfwjs/core";
import { MobileNetV2Model } from "nsfwjs/models/mobilenet_v2";
import { MobileNetV2MidModel } from "nsfwjs/models/mobilenet_v2_mid";

const model = await load("MobileNetV2", {
  modelDefinitions: [MobileNetV2Model, MobileNetV2MidModel],
});

If you pass an empty model registry, named bundled model loads will fail:

javascript
await load("MobileNetV2", { modelDefinitions: [] }); // throws

Library API

load the model

Before you can classify any image, you'll need to load the model.

javascript
const model = nsfwjs.load(); // Default: "MobileNetV2"

You can use the optional first parameter to specify which model you want to use from the three built-in bundled models. Defaults to: "MobileNetV2".

For tree-shaken selective model bundling, use nsfwjs/core and pass modelDefinitions as shown above.

javascript
const model = nsfwjs.load("MobileNetV2Mid"); // "MobileNetV2" | "MobileNetV2Mid" | "InceptionV3"

You can also use same parameter and load the model from your website/server, as explained in the Host your own model section. Doing so could reduce the bundle size for loading the model by approximately 1.33 times (33%) since you can directly use the binary files instead of the base64 that are bundled with the package. i.e. The "MobileNetV2" model bundled into the package is 3.5MB instead of 2.6MB for hosted binary files. This would only make a difference if you are loading the model every time (without Caching) on the client-side browser since on the server-side, you'd only be loading the model once at the server start.

If you are hosting your own model via URL and want the smallest app bundle, import load from nsfwjs/core instead of nsfwjs. The core entrypoint does not include built-in model definitions by default, so bundlers do not pull those model assets into your app bundle.

javascript
import { load } from "nsfwjs/core";

const model = await load("/path/to/mobilenet_v2/model.json");

Model MobileNetV2 - 224x224

javascript
const model = nsfwjs.load("/path/to/mobilenet_v2/");

If you're using a model that needs an image of dimension other than 224x224, you can pass the size in the options parameter.

Model MobileNetV2Mid - Graph

javascript
/* You may need to load this model with graph type */
const model = nsfwjs.load("/path/to/mobilenet_v2_mid/", { type: 'graph' });

If you're using a graph model, you cannot use the infer method, and you'll need to tell model load that you're dealing with a graph model in options.

Model InceptionV3 - 299x299

javascript
const model = nsfwjs.load("/path/to/inception_v3/", { size: 299 });

Caching

If you're using in the browser and you'd like to subsequently load from indexed db or local storage (NOTE: model size may be too large for local storage!) you can save the underlying model using the appropriate scheme and load from there.

javascript
const initialLoad = await nsfwjs.load(
  "/path/to/different/model/" /*, { ...options }*/
);
await initialLoad.model.save("indexeddb://exampleModel");
const model = await nsfwjs.load("indexeddb://exampleModel" /*, { ...options }*/);

Parameters

Initial Load:

  1. URL or path to folder containing model.json.
  2. Optional object with size or type property that your model expects.

Subsequent Load:

  1. IndexedDB path.
  2. Optional object with size or type property that your model expects.

Returns

  • Ready to use NSFWJS model object

Troubleshooting

  • On the tab where the model is being loaded, inspect element and navigate to the the "Application" tab. On the left pane under the "Storage" section, there is a subsection named "IndexedDB". Here you can view if the model is being saved.

For a complete browser worker implementation (including backend initialization, IndexedDB-first load, and save-on-miss caching), see examples/nsfw_demo/src/nsfwjs.worker.ts.

classify an image

This function can take any browser-based image elements (``, <video>, <canvas>) and returns an array of most likely predictions and their confidence levels.

javascript
// Return top 3 guesses (instead of all 5)
const predictions = await model.classify(img, 3);

Parameters

  • Tensor, Image data, Image element, video element, or canvas element to check
  • Number of results to return (default all 5)

Returns

  • Array of objects that contain className and probability. Array size is determined by the second parameter in the classify function.

dispose a loaded model

If you are done with a model instance, call dispose() to release held tensors and model resources.

javascript
const model = await nsfwjs.load();
// ... classify/infer
model.dispose();

Production

Tensorflow.js offers two flags, enableProdMode and enableDebugMode. If you're going to use NSFWJS in production, be sure to enable prod mode before loading the NSFWJS model.

javascript
import * as tf from "@tensorflow/tfjs";
import * as nsfwjs from "nsfwjs";
tf.enableProdMode();
//...
let model = await nsfwjs.load(`${urlToNSFWJSModel}`);

NOTE: Consider downloading and hosting the model yourself before moving to production as explained in the Host your own model section. This could potentially improve the initial load time of the model. Furthermore, consider Caching the model, if you are using it in the browser.

Backend selection

NSFWJS uses whichever TensorFlow.js backend is active.

Setting a backend explicitly is optional. If you import one or more backends and call await tf.ready(), TensorFlow.js will pick the best available backend.

Use tf.setBackend(...) only when you want deterministic behavior across devices.

Automatic backend selection:

javascript
import * as tf from "@tensorflow/tfjs";
import "@tensorflow/tfjs-backend-webgpu";
import "@tensorflow/tfjs-backend-wasm";
import * as nsfwjs from "nsfwjs";

await tf.ready();

const model = await nsfwjs.load();

Pinned backend selection:

javascript
import * as tf from "@tensorflow/tfjs";
import "@tensorflow/tfjs-backend-webgpu";

await tf.setBackend("webgpu");
await tf.ready();

WASM backend (optional)

bash
yarn add @tensorflow/tfjs-backend-wasm
javascript
import * as tf from "@tensorflow/tfjs";
import {
  setWasmPaths,
} from "@tensorflow/tfjs-backend-wasm";
import "@tensorflow/tfjs-backend-wasm";

// If you aren't using a standard bundler, set the path to the .wasm binaries.
setWasmPaths("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm/dist/");

await tf.setBackend("wasm");
await tf.ready();

WebGPU backend (optional)

bash
yarn add @tensorflow/tfjs-backend-webgpu
javascript
import * as tf from "@tensorflow/tfjs";
import "@tensorflow/tfjs-backend-webgpu";

await tf.setBackend("webgpu");
await tf.ready();

Backend guidance:

  • webgpu: often fastest on supported browsers/hardware.
  • webgl: strong default in modern desktop/mobile browsers.
  • wasm: useful fallback for environments where WebGL is unavailable/restricted.
  • cpu: broad compatibility but typically slower.

Node.js backend

For Node.js workloads, consider using @tensorflow/tfjs-node (or @tensorflow/tfjs-node-gpu where applicable) for better performance. See the Node JS App section for examples.

Always benchmark in your target browser/device set.

Install

NSFWJS is powered by TensorFlow.js as a peer dependency. If your project does not already have TFJS you'll may want to add it.

bash
# peer dependency
$ yarn add @tensorflow/tfjs
# install NSFWJS
$ yarn add nsfwjs

For script tags include all the bundles as shown here. Then simply access the nsfwjs global variable. This requires that you've already imported TensorFlow.js as well.

Host your own model

The magic that powers NSFWJS is the NSFW detection model. By default, the models are bundled into this package. But you may want to host the models on your own server to reduce bundle size by loading them as raw binary files or to host your own custom model. If you want to host your own version of the model files, you can do so by following the steps below. You can then pass the relative URL to your hosted files in the load function along with the options if necessary.

If you are loading a hosted model URL, prefer nsfwjs/core so your app does not bundle built-in model definitions. See Selective model bundles (tree-shaking).

Here is how to install the default model on a website:

  1. Download the project by either downloading as zip or cloning `git clone https://github.com/in

Issues· 93 open

View all issuesOpen on GitHub
  • #939

    Agent M

    Updated Sep 28, 2026
  • #934

    Nude filter rather than sexy

    Updated Jul 27, 2026
  • #741

    [Node.JS] Memory leak - Server reaches 100% memory after 5 or 6 days

    Updated May 18, 2026
  • #926

    Converting mobilenet_v2_mid to tflite

    Updated Dec 24, 2025
  • #924

    Model is having issues identifying Men between sexy and neutral

    Updated Jun 7, 2025
  • #792

    Not work local model load

    Updated May 28, 2025
  • #599

    Unable to use in service workers in manifest v3

    bugExtension IssuesUpdated May 25, 2025
  • #920

    False negative: Inappropriate South Park images classed as Drawing / Neutral

    Updated Feb 16, 2025
  • #918

    False Positive: AI-Generated Porn Images Misclassified as 'Sexy' Instead of 'Porn'

    enhancementUpdated Jan 28, 2025
  • #893

    Website using this to detect NSFW detects my Profile Picture as NSFW

    False PositivesUpdated Jan 23, 2025

> Tags

TypeScriptcontent-managementjavascriptmachine-learningmachinelearning

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言