M1chlCZ/nsfw_sherlock
Sobre
Free, self-hosted image moderation API in Go. Check NSFW images on your own server with HTTP, gRPC, Docker, and optional OCR. No subscription or per-image API fees.
Design e mídiaCrescimento medido de estrelas
- em 24 h
- 0
- em 7 dias
- 0
- em 15 dias
- 0
- em 1 mês
- Coletando histórico
Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.
README.md
Original
NSFW Sherlock
Free, self-hosted image moderation.
Run it on your server. Keep image analysis local.
NSFW Sherlock is a free, open-source API that checks images for NSFW content on your own hardware. It has no subscription or per-image API fees. You cover your own hardware and hosting costs.
- Self-hosted: Image analysis runs on your server, without an external moderation API.
- Easy to connect: Use HTTP or gRPC from your application, or send an image URL.
- Image checks: Classify photos and anime, and detect explicit regions. Animated GIFs and videos are sampled across their frames.
- Policies: Pick
strict,balancedorlenient, or write per-label thresholds for your product. - Explainable: See which score crossed which threshold, and get an annotated image with the detecting regions.
- Scan a folder: Analyze a directory offline and write an HTML review report or JSONL, with policy comparison and labeled evaluation.
- Python SDK:
pip install nsfw-sherlockfor a typed client. - Optional OCR: Use Tesseract to detect words in images.
- Docker and Helm: Full, slim and commercial-safe images, plus a Kubernetes chart.
One Go binary runs the models with ONNX Runtime. The code uses AGPL-3.0. Model licenses apply separately.
Run with Docker
Run the CPU image:
docker run -e APP_ENV=web -p 4000:4000 m1chl/nsfw-sherlock
Make sure that the service responds:
curl http://localhost:4000/ping
The image includes the models and OCR support. It supports Linux amd64 and arm64. Docker Hub and GHCR publish the same images.
The full image contains every model. latest-slim contains only the
balanced models (about 440 MB less model data), and latest-commercial
contains only the MIT-licensed photo and anime models, with no region
detector. See Model profiles for the licensing details.
For gRPC, set APP_ENV=grpc. The default interface is HTTP.
Run a release binary
The releases page has archives for Linux amd64, Linux arm64, and macOS arm64, with checksums. The binaries do not include OCR support.
Clone the repository and unpack the archive into it. Then download the models and the runtime:
scripts/fetch-models.sh --ort-only
scripts/fetch-models.sh
./nsfw-sherlock
The same binary has an offline scan command; see Scan a folder.
Deploy on Kubernetes
The Helm chart deploys the CPU image with probes, a rolling update, resource requests, an optional ingress, autoscaling, a PodDisruptionBudget and a Secret for API keys:
helm install nsfw-sherlock deploy/helm/nsfw-sherlock \
--set 'auth.apiKeys[0]=replace-me' \
--set ingress.enabled=true \
--set ingress.hosts[0].host=moderation.example.com \
--set-json 'policies={"fashion":{"porn_explicit":0.75,"sexy_suggestive":0.9}}'
The chart renders the policies map into a ConfigMap and sets POLICIES_FILE.
Use --set-json for numeric policy values.
Set config.ORT_PROVIDER=cuda, add nvidia.com/gpu to
resources.limits, and select a GPU node with nodeSelector for the CUDA
image. The chart defaults to two replicas and no API keys; set a key before
exposing the service.
API
All image endpoints accept this JSON request:
{"base64":"<base64-encoded image>","filename":"image.jpg","policy":"balanced"}
policy is optional and names a decision policy. sensitivity still scales
the chosen policy's thresholds.
Send "url":"https://example.com/image.jpg" instead of base64 to let the
service fetch the image. Send exactly one of the two fields. A URL fetch is
limited to MAX_IMAGE_BYTES, follows at most three redirects, and rejects
private, loopback and link-local addresses unless URL_ALLOW_PRIVATE=true.
The URL guard also checks the resolved address when it dials, so a redirect or
a rebinding answer cannot reach an internal service.
Set sensitivity between 0.1 and 10 to change the decision thresholds. Higher values flag more images. The default is 1. The gRPC requests have the same field.
With API_KEYS, every image endpoint requires the key in the X-API-Key header. /ping, /ready, /metrics and /openapi.json stay open.
| HTTP endpoint | Response |
|---|---|
GET /ping |
Service status |
GET /ready |
Readiness probe; reports whether video scanning is available |
GET /metrics |
Prometheus metrics |
GET /openapi.json |
OpenAPI 3.1 description of this API |
POST /pic/check |
nsfwPic and nsfwText flags |
POST /pic/labels |
Probabilities for drawings, hentai, neutral, porn, and sexy |
POST /pic/analyze |
Full analysis, model scores, region detections, reasons, and elapsed time |
POST /pic/annotate |
PNG or JPEG with detection boxes, labels and a verdict badge |
POST /pic/batch |
One /pic/check result per image, up to BATCH_MAX_IMAGES |
POST /pic/upload |
Raw image bytes as the request body; the same body as /pic/check |
POST /video/check |
Multipart video upload; one analysis per sampled frame and a summary |
POST /jobs |
Start a background batch or video analysis |
GET /jobs |
Kept background jobs, newest first, with state counts |
GET /jobs/{id} |
Job state and result |
GET /jobs/{id}/events |
Server-sent events for a job's state changes |
DELETE /jobs/{id} |
Cancel a queued job or a running analysis |
Example response from /pic/check:
{"status":"ok","message":"success","nsfwText":false,"nsfwPic":false}
The full analysis includes a verdict (sfw, suggestive, or explicit) and an nsfw score.
Errors use {"errorMessage":"...","status":"FAIL","hasError":true}.
The batch endpoint accepts {"images":[<the request above>, ...]} and returns {"status":"ok","message":"success","results":[...]}.
Each result is a /pic/check body or the error body.
The default limit is 4 images.
Send multipart form data instead with one file field per image and an optional sensitivity field for the whole batch:
curl -fsS -F "[email protected]" -F "[email protected]" -F "sensitivity=1.5" \
http://localhost:4000/pic/batch
When CACHE_ENTRIES is greater than 0, the service stores responses for identical image bytes and returns them again without running the models.
Verdict reasons
When the verdict is suggestive or explicit, /pic/analyze adds a
reasons array. Each entry names the rule, the score, the effective
threshold after the sensitivity scale, and the verdict it supports:
{
"verdict": "explicit",
"nsfw": 0.91,
"reasons": [
{"rule":"label","label":"porn","score":0.91,"threshold":0.5,"verdict":"explicit"},
{"rule":"detection","label":"FEMALE_BREAST_EXPOSED","score":0.88,"threshold":0.3,"verdict":"explicit"}
]
}
Only rules that support the final verdict are listed, at most eight, highest score first. A safe image keeps its previous response shape.
Policies
Three policies ship with the service: strict, balanced and lenient.
balanced keeps the original thresholds. NSFW_POLICY sets the default, and
an HTTP request can override it with "policy".
A JSON file adds or replaces policies:
{
"version": 1,
"policies": {
"fashion": {
"porn_explicit": 0.75,
"hentai_explicit": 0.8,
"sexy_suggestive": 0.9,
"anime_r15_suggestive": 0.9,
"detection_explicit": 0.5,
"detection_suggestive": 0.8,
"ignored_classes": ["BELLY_EXPOSED"]
}
}
}
POLICIES_FILE=/etc/nsfw-sherlock/policies.json NSFW_POLICY=fashion ./nsfw-sherlock
Every field is optional and inherits balanced. explicit_classes and
suggestive_classes replace the detector classes used for the verdict;
ignored_classes removes classes from both. The policy name is echoed in
/pic/analyze, the reasons use its thresholds, and the scan report records it.
The Helm chart renders a policies map into a ConfigMap; use --set-json for
numeric overrides.
Annotated evidence
/pic/annotate returns the image with a verdict badge, one box per detection,
and the class and score on each box. The response headers repeat the verdict,
score, policy and box count. For an animated GIF it annotates the frame that
produced the verdict. Nothing is stored.
curl -fsS -X POST http://localhost:4000/pic/annotate \
-H 'Content-Type: application/json' \
-d '{"url":"https://example.com/upload.jpg","maxWidth":1280,"format":"png"}' \
-o evidence.png
maxWidth is between 320 and 4096 (default 1280). format is png (default)
or jpeg. Use the response as the moderation preview in a review tool, or
open it next to the original when a user appeals a decision.
Image URLs
Most endpoints accept a public image URL in place of base64:
curl -fsS -X POST http://localhost:4000/pic/check \
-H 'Content-Type: application/json' \
-d '{"url":"https://example.com/upload.jpg"}'
The guard rejects credentials in the URL, non-HTTP schemes and private
networks, including a redirect to one. Set URL_ALLOW_PRIVATE=true only when
your images live on a trusted internal host.
The batch endpoint accepts a mix of base64 and url entries. The gRPC
service keeps its base64 request and is unchanged in this release.
Video scanning
POST /video/check accepts a multipart form with the video in the file
field. The service probes the duration with ffprobe and samples at most
VIDEO_SAMPLE_FPS frames per second, capped at VIDEO_MAX_FRAMES (default
24). For a long video the effective rate is lowered so the frames cover the
whole duration, not just the beginning. Analysis stops after an explicit frame
and reports earlyExit in the summary. The response returns the worst verdict:
curl -fsS -F "[email protected]" http://localhost:4000/video/check
The response holds summary (verdict, maximum NSFW score, frame counts,
earlyExit and elapsed time) and frames, with one analysis per analyzed
frame. Install ffmpeg and ffprobe on the host, or use the Docker image, which
includes both. Without ffmpeg the endpoint answers 503; without ffprobe the
sampler falls back to the start of the video. Uploads are limited to
VIDEO_MAX_BYTES and the whole scan stops after 120 seconds.
Every response carries an X-Request-ID header. JSON logs repeat it as requestId.
With RATE_LIMIT_RPM set, limited responses also carry X-RateLimit-Limit,
X-RateLimit-Remaining, and X-RateLimit-Reset (Unix seconds); a 429 adds
Retry-After.
Async jobs
Large batches and videos can run in the background. POST /jobs accepts the
same JSON body as /pic/batch, or a multipart video in the file field:
curl -fsS -X POST http://localhost:4000/jobs \
-H "Content-Type: application/json" -d '{"images":[...]}'
curl -fsS -F "[email protected]" http://localhost:4000/jobs
The service answers 202 with a job id. Poll GET /jobs/{id} for the state
(queued, running, done, failed or canceled) and the result.
DELETE /jobs/{id} cancels a queued job or a running analysis.
Job callbacks
Add callbackUrl to a batch job, or a callbackUrl form field to a video
job, to receive the result without polling:
curl -fsS -X POST http://localhost:4000/jobs \
-H "Content-Type: application/json" \
-d '{"images":[...],"callbackUrl":"https://example.com/hooks/nsfw"}'
curl -fsS -F "[email protected]" -F "callbackUrl=https://example.com/hooks/nsfw" \
http://localhost:4000/jobs
When the job reaches done or failed, the service posts this JSON body to
the callback URL:
{"event":"job.finished","job":{...the same shape as GET /jobs/{id}...}}
The request carries X-NSFW-Event, X-NSFW-Job-ID, and, when
WEBHOOK_SECRET is set, X-NSFW-Timestamp and X-NSFW-Signature. The
signature is sha256= followed by the hex HMAC-SHA256 of
<timestamp>.<body> with the secret as the key.
Callbacks retry on network errors and non-2xx answers. WEBHOOK_RETRIES sets
the number of retries after the first attempt, and WEBHOOK_TIMEOUT_SECONDS
bounds each attempt. Redirects are not followed. Private, loopback, and
link-local addresses are rejected unless WEBHOOK_ALLOW_PRIVATE=true.
GET /jobs lists the kept jobs newest first. Pass state to filter
(queued, running, done, failed or canceled) and limit to cap the
result; the default is 100. The counts field always covers every kept job.
GET /jobs/{id}/events streams the state changes with server-sent events:
curl -N http://localhost:4000/jobs/<id>/events
Each event is named after the state and carries the same body as
GET /jobs/{id}. The stream ends when the job finishes. A keepalive comment
every 15 seconds keeps the connection open.
JOB_WORKERS sets how many jobs run at once, JOB_MAX_ENTRIES caps the kept
jobs, and JOB_TTL_SECONDS sets how long a finished job stays. The defaults
are 2 workers, 64 jobs, and 600 seconds.
The nsfw_request_duration_seconds histogram carries an endpoint label.
The /metrics output also includes nsfw_jobs_submitted_total,
nsfw_jobs_rejected_total, nsfw_jobs_current, nsfw_jobs_finished_total,
and nsfw_job_duration_seconds. Callback delivery counters are
nsfw_webhook_deliveries_total and nsfw_webhook_failures_total.
GET /ready reports whether video scanning is available.
The gRPC service exposes Detect, DetectLabels, and Analyze.
It also serves the standard gRPC health service and server reflection.
The service definition contains the request and response types.
Scan a folder
The same binary can scan images and directories without starting the server. It writes a self-contained HTML report with a verdict summary, a table of every file, and annotated previews of the images that need review:
./nsfw-sherlock scan ~/Pictures/import \
--out nsfw-report.html \
--jsonl nsfw-report.jsonl \
--workers 4
scanned 1284 files in 182034 ms: 1201 safe, 62 suggestive, 19 explicit, 2 errors
report: nsfw-report.html
jsonl: nsfw-report.jsonl
| Flag | Default | Meaning |
|---|---|---|
--out |
nsfw-report.html |
HTML report path |
--jsonl |
(none) | One JSON object per file, for pipelines |
--workers |
2 |
Concurrent analyses (1..32) |
--recursive |
true |
Walk directories; use --recursive=false for one level |
--fail-on |
off |
Exit 1 on explicit, suggestive or error |
--no-thumbnails |
false |
Leave images out of the report |
--max-thumbnails |
200 |
Largest number of previews embedded |
--sensitivity |
1 |
Threshold scale between 0.1 and 10 |
--policy |
environment | Decision policy: strict, balanced, lenient or a configured policy |
--compare-policies |
(none) | Comma-separated policies for a comparison report |
--labels |
(none) | CSV of path,label for a comparison evaluation |
--profile |
environment | Model profile, such as balanced, max, fast, compat or commercial |
--provider |
environment | cpu, cuda, migraphx, tensorrt or openvino |
--progress |
false |
Print every file to stderr |
Explicitly named files are analyzed even with an unknown extension; directory walks use the usual image extensions. A file that cannot be read or analyzed becomes an error row and does not stop the scan.
The report embeds the flagged images as JPEG previews so it is self-contained.
It is written with owner-only permissions; keep it private, or pass
--no-thumbnails when the report will be shared. The exit code is 0 for a
completed scan, 1 when --fail-on matches, and 2 for a usage or setup error.
Use --fail-on suggestive in a dataset pipeline to reject a batch before it
is published:
./nsfw-sherlock scan ./dataset --no-thumbnails --jsonl results.jsonl --fail-on explicit
The scan command does not run OCR, does not store images, and does not call the network.
GPU support
NVIDIA · CUDA
Install an NVIDIA driver compatible with CUDA 13.0 and the NVIDIA Container Toolkit. Then run the CUDA image:
docker run --gpus all -p 4000:4000 m1chl/nsfw-sherlock:v1.6.0-cuda
This image supports Linux amd64. It includes ONNX Runtime 1.31.1, CUDA 13, and cuDNN.
ORT_DEVICE_ID selects the GPU index, with 0 as the default.
AMD · ROCm / MIGraphX
Install ROCm and a MIGraphX-enabled ONNX Runtime 1.29.0 shared library.
Set ORT_PROVIDER=rocm.
Point ORT_LIB to that library.
Keep the provider libraries beside it.
Add the ROCm dependencies to the library search path.
The rocm value is an alias for migraphx. The Go binding requires ORT API 29.
Older runtimes are incompatible. This project does not publish an AMD image.
The MIGraphX guide describes the runtime build.
NVIDIA · TensorRT
Use an ONNX Runtime shared library built with the TensorRT execution provider.
Then set ORT_PROVIDER=tensorrt.
TensorRT compiles each model for your GPU at the first run. This step is slow.
Intel · OpenVINO
Use an ONNX Runtime shared library built with the OpenVINO execution provider.
Then set ORT_PROVIDER=openvino.
OpenVINO runs on an Intel CPU or GPU.
If the selected provider is unavailable, the service stops at startup. Unsupported operators can still use the CPU. The v1.0.5 Linux amd64 binary passed a physical CUDA test on an RTX 5070 Ti under WSL2, with ONNX Runtime 1.29.0, CUDA 13 and cuDNN 9.24. See the test setup, results and reproduction client. This test does not cover the CUDA 13 Docker image, AMD/MIGraphX, TensorRT or OpenVINO.
Configuration
| Variable | Default | Purpose |
|---|---|---|
APP_ENV |
web |
HTTP (web) or gRPC (grpc). http is a deprecated alias. |
PORT |
4000 |
Service port |
NSFW_PROFILE |
balanced |
Model profile |
NSFW_POLICY |
balanced |
Default decision policy |
POLICIES_FILE |
(none) | JSON file with additional policies |
ORT_PROVIDER |
cpu |
cpu, cuda, migraphx, tensorrt, or openvino. rocm aliases migraphx. |
ORT_DEVICE_ID |
0 |
GPU index |
OCR_ENABLED |
true |
Text detection. Requires a build with OCR support. |
API_KEYS |
(none) | Comma-separated keys for the X-API-Key header. Empty disables the check. |
RATE_LIMIT_RPM |
0 |
Requests per minute for each key or IP. 0 disables the limit. |
URL_ALLOW_PRIVATE |
false |
Allow image URLs on private and loopback addresses |
Paths, limits, and logging
| Variable | Default | Purpose |
|---|---|---|
MODELS_DIR |
./assets/models |
Model directory |
MANIFEST |
models/manifest.json |
Model manifest |
ORT_LIB |
Auto-detected | ONNX Runtime shared library path |
BAD_WORDS_FILE |
Auto-detected | OCR word list. Uses an embedded list as a fallback. |
MAX_IMAGE_BYTES |
20971520 (20 MiB) |
Maximum image size |
MAX_IMAGE_PIXELS |
50000000 |
Maximum decoded pixel count |
SESSION_POOL_SIZE |
2 |
Sessions per model |
BATCH_MAX_IMAGES |
4 |
Images per /pic/batch request (1..64). Raises the request body limit. |
CACHE_ENTRIES |
0 |
Stored responses for identical image bytes. 0 disables the cache. |
JOB_WORKERS |
2 |
Background jobs that run at once (1..32) |
JOB_MAX_ENTRIES |
64 |
Kept background jobs (1..10000) |
JOB_TTL_SECONDS |
600 |
Seconds a finished job stays available (1..86400) |
WEBHOOK_SECRET |
(none) | HMAC-SHA256 key for callback signatures. Empty disables signing. |
WEBHOOK_TIMEOUT_SECONDS |
10 |
Seconds per callback attempt (1..60) |
WEBHOOK_RETRIES |
3 |
Retries after a failed callback attempt (0..10) |
WEBHOOK_ALLOW_PRIVATE |
false |
Allow callback URLs on private and loopback addresses |
FFMPEG_PATH |
ffmpeg |
ffmpeg binary used by /video/check |
FFPROBE_PATH |
ffprobe |
ffprobe binary used to sample the whole video |
VIDEO_SAMPLE_FPS |
1 |
Maximum frames sampled per second (0.1..30) |
VIDEO_MAX_FRAMES |
24 |
Frame cap per video (1..240) |
VIDEO_MAX_BYTES |
67108864 (64 MiB) |
Maximum video upload |
NSFW_ALLOW_DEGRADED |
false |
Allow startup after a required model fails to load. |
LOG_LEVEL |
info |
debug, info, warn, or error |
LOG_FORMAT |
text |
text or json |
Docker images supply the model and runtime paths. They use JSON logs.
Model profiles
| Profile | Photo model | Anime model | Region detector |
|---|---|---|---|
balanced (default) |
Freepik EVA02 | CaFormer | NudeNet 320px |
max |
Freepik EVA02 | CaFormer | NudeNet 640px |
fast |
Freepik EVA02 | MobileNetV3 | NudeNet 320px |
compat |
ViT5 with five legacy labels | None | None |
commercial |
Freepik EVA02 | CaFormer | None |
commercial uses only the MIT-licensed photo and anime models, so it returns
no region detections. The code is still AGPL-3.0; model licenses are listed
below and dual licensing is a separate decision. The compat profile uses the
non-commercial ViT5 model.
Python SDK
The MIT-licensed client wraps the HTTP API with typed responses, retries and policy support:
pip install nsfw-sherlock
from pathlib import Path
from nsfw_sherlock import Client
with Client("http://localhost:4000", api_key="optional-key") as client:
analysis = client.analyze(Path("photo.jpg"), policy="strict")
print(analysis.verdict, analysis.policy, analysis.reasons)
Path("evidence.png").write_bytes(client.annotate(Path("photo.jpg")))
The SDK lives in sdk/python and versions independently of the server.
Build from source
Requirements: Go 1.27, a C compiler, Python 3, and curl. Video scanning needs ffmpeg and ffprobe at runtime. The runtime download supports Linux amd64, Linux arm64, and macOS arm64.
Download the source, runtime, and models. Then build the binary. Run the binary:
git clone https://github.com/M1chlCZ/nsfw_sherlock
cd nsfw_sherlock
scripts/fetch-models.sh --ort-only
scripts/fetch-models.sh
go build .
./nsfw_sherlock
The download script uses pinned SHA-256 digests for the runtime and models.
The engine also compares each model digest with the manifest at startup.
This source build excludes OCR and always reports nsfwText: false.
For OCR support, install Tesseract, Leptonica, their development libraries, and the English language data. Then build with the OCR tag:
go build -tags ocr .
OCR_ENABLED=false also disables text detection.
Development
Run the tests and lint checks:
go test ./... -count=1 -race
go test -tags ocr ./... -count=1 -race
golangci-lint run
golangci-lint run --build-tags ocr
PARITY_REQUIRE=1 go test ./engine -run TestParity
The OCR tests require Tesseract. The parity tests require the models and ONNX Runtime.
CI also runs go vet, govulncheck, a Docker smoke test that covers /pic/annotate, policy requests and scan, a Helm lint job and the Python SDK tests.
Release jobs require successful CI checks before they publish images.
The lint configuration adapts the Golden config.
Model tools: manifest · download · export · parity fixtures · benchmark.
Stub generation uses make proto.
Models and licenses
The code uses AGPL-3.0. Model licenses apply separately.
| Model | License |
|---|---|
| Freepik photo classifier | MIT |
| deepghs anime classifiers | MIT |
| NudeNet region detectors | AGPL-3.0 |
| ViT5 compatibility classifier | CC-BY-NC-ND-4.0 |
Review the model licenses before commercial use.
The compat model has non-commercial and no-derivatives restrictions.
Review its license before you export or redistribute it.
Runtime: onnxruntime_go. OCR: gosseract and Tesseract.
Support
If this project helps you, you can support its development.
If this project helps you, consider giving it a star. Bug reports and contributions are welcome.
Explore projetos relacionados
Carregando…