- C 93.1%
- Shell 5.2%
- Makefile 1.7%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| models | ||
| src | ||
| tests | ||
| .gitignore | ||
| config.ini | ||
| CUDA_INFERENCE.md | ||
| Makefile | ||
| OPENVINO_INFERENCE.md | ||
| README.md | ||
nnsort
nnsort sorts images and videos by object-detection labels. It uses the
NudeNet detector through ONNX Runtime,
decodes media with FFmpeg, and moves each file into the first configured rule
directory that matches.
Features
- Images and videos in one input tree.
- Recursive scanning with preserved relative paths:
input/a/b.jpg→output/fg/a/b.jpg. Use--no-preserve-pathto place files directly in the target directory instead. - Ordered label rules: match any or all of several labels per rule, with
optional
!exclusions; the first matching rule wins. - Fuzzy label abbreviations such as
ff,fge, and!mge, expanded to full NudeNet names and confirmed before scanning. defaultfallback when no configured rule matches.- Move by default;
--copyleaves the source in place. - Atomic no-overwrite moves and temp-file-based copies.
- Existing destination files are skipped, never overwritten. Use
--rename-on-conflictto add a numeric suffix instead (name (1).jpg). - Video sampling at a configurable interval (default: every 2 seconds).
- Batched inference across images and video frames.
- Optional early stop when the highest-priority rule matches.
- Single-file detection mode that never changes the input.
- Optional annotated output with boxes, labels, and confidence scores.
- Annotated videos preserve the primary audio stream.
- Dry-run mode.
- Works with NudeNet
models/320n.onnxandmodels/640m.onnx. - Optional hardware-accelerated video decoding (VAAPI, CUDA, QSV, VDPAU, VideoToolbox, and other FFmpeg device types) with automatic software fallback.
Requirements
- Linux/POSIX
- C11 compiler (
gccorclang) - GNU Make
pkg-config- FFmpeg development libraries:
libavformat,libavcodec,libavutil,libswscale - ONNX Runtime development headers and shared library (
libonnxruntime.so) (the default build embedsmodels/320n.onnx; no model file is needed at runtime)
Hardware video decoding is optional. It needs a working GPU driver and the
matching FFmpeg hardware device support (for example VAAPI on Intel/AMD,
NVIDIA's CUDA/NVDEC stack, or vendor QSV/VDPAU drivers). Without it, nnsort
uses software decoding automatically.
On Debian/Ubuntu the FFmpeg packages are typically:
sudo apt install build-essential pkg-config \
libavformat-dev libavcodec-dev libavutil-dev libswscale-dev
The project expects the ONNX Runtime header at
<onnxruntime/onnxruntime_c_api.h> and links with -lonnxruntime. If ONNX
Runtime is installed in a custom prefix:
make ORT_CFLAGS="-I/opt/onnxruntime/include" \
ORT_LIBS="-L/opt/onnxruntime/lib -lonnxruntime"
Build
make
The default build embeds models/320n.onnx into the executable. To embed a different
model, or to build without an embedded model:
make EMBED_MODEL=models/640m.onnx # embeds the larger model; expect a much bigger binary
make EMBED_MODEL= # no embedded model; use --model PATH at runtime
Other targets:
make debug # -O0 -g3
make san # AddressSanitizer + UndefinedBehaviorSanitizer
make test # config parser and priority unit tests
make smoke # generated image/video end-to-end test
make clean
Model
models/320n.onnx from NudeNet v3.4 is included in this repository and is embedded in
the default build. At runtime the model file is not needed.
The model is selected on the command line, never in the config file:
# Use the embedded 320n model (default).
./nnsort -i /media/in -o /media/out
# Use an external model with its matching input resolution.
./nnsort -i /media/in -o /media/out \
--model ./models/640m.onnx --resolution 640
--model PATH overrides the embedded model; the path is relative to the
current working directory. --resolution N sets the input size for dynamic
models; if omitted, 320 is used. Use --model with --resolution 640 for
models/640m.onnx.
Configuration
# Rules are evaluated top-to-bottom. The first matching rule wins.
# A comma means "any of these labels"; a plus means "all of them".
# Prefix a label with ! to require it to be absent.
# Target paths are relative to the output directory.
[labels]
MALE_GENITALIA_EXPOSED, FEMALE_GENITALIA_EXPOSED = "./genitalia"
ff + fge + !mge = "./female"
FEET_EXPOSED = "./feet"
BUTTOCKS_EXPOSED + !ANUS_EXPOSED = "./butts"
default = "./other"
Model selection is command-line only; a [model] section is rejected.
Rules:
[labels]order defines priority.- A comma-separated rule matches when any required listed label was detected.
- A
+-separated rule matches only when all required labels were detected. - A label prefixed with
!is negated: it must not be detected anywhere in the sampled frames. - Negated labels are always ANDed. The comma/plus choice only affects positive
labels, so
BUTTOCKS_EXPOSED, !ANUS_EXPOSEDmeans “BUTTOCKS_EXPOSEDand notANUS_EXPOSED”. - A rule may contain only negated labels; it matches when none of them were detected.
- Comma and
+cannot be mixed in one rule; use separate rules with the same target if needed. - The first matching rule wins; detection order or confidence does not override the config order.
defaultis used only when no rule matched.- If there is no
defaultand no rule matched, the file is left in place. - Positive labels only need to appear somewhere in the sampled frames, not necessarily in the same frame.
- Target paths must be relative to the output directory. Absolute paths and
..components are rejected. - Label names are case-insensitive; target paths are case-sensitive.
- Labels may be abbreviated when writing rules:
- One letter per underscore-separated word:
ff→FACE_FEMALE,fge→FEMALE_GENITALIA_EXPOSED,mge→MALE_GENITALIA_EXPOSED. _-separated word prefixes resolve collisions:belly_e→BELLY_EXPOSED,butt_c→BUTTOCKS_COVERED,face_f→FACE_FEMALE.- If no acronym matches, a label-name prefix is tried, for example
buttfinds bothBUTTOCKS_EXPOSEDandBUTTOCKS_COVERED.
- One letter per underscore-separated word:
- An abbreviation that matches more than one label is an error and lists the candidates; write a longer underscore-separated form or the full name.
- Fuzzy rules are expanded in memory, printed before the scan, and require
confirmation. Use
--yesto skip the prompt. Without a terminal and without--yes, the program aborts instead of waiting for input. The config file is never rewritten. - Required labels must be unique across rules. Negated labels may be reused across rules, including alongside a rule that requires the same label.
- A label cannot be both required and negated in the same rule.
- Duplicate required labels, duplicate negated labels in one rule, duplicate
default, unknown labels, malformed values, empty list entries, and mixed operators are configuration errors. - Full-line
#/;comments are supported. Inline comments are not stripped. [labels]is optional for detection mode, so a config with no sections is valid with--detect. Sorting mode still requires rules or adefault.
Rules on the command line
Rules can be supplied without a config file:
./nnsort -i /media/in -o /media/sorted -r "fge+!mge=./female"
./nnsort -i /media/in -o /media/sorted \
--rule "ff, fm=./faces" --rule "!mge=./other"
-r/--ruleis repeatable; rules are evaluated in the order given.- The
LABELS=TARGETsyntax, fuzzy abbreviations,,,+, and!behave exactly as in[labels]. - When at least one
--ruleis given, the config file is ignored, including an explicit--config. --default DIRsets the fallback target. With--rule, it is the only fallback because the config is ignored. Without--rule, it overrides the loaded config'sdefault.- Without a
default, files that match no rule are left in place.
All NudeNet labels are accepted:
FEMALE_GENITALIA_COVERED
FACE_FEMALE
BUTTOCKS_EXPOSED
FEMALE_BREAST_EXPOSED
FEMALE_GENITALIA_EXPOSED
MALE_BREAST_EXPOSED
ANUS_EXPOSED
FEET_EXPOSED
BELLY_COVERED
FEET_COVERED
ARMPITS_COVERED
ARMPITS_EXPOSED
FACE_MALE
BELLY_EXPOSED
MALE_GENITALIA_EXPOSED
ANUS_COVERED
FEMALE_BREAST_COVERED
BUTTOCKS_COVERED
Usage
Usage: nnsort -i DIR [options]
nnsort --detect FILE [--draw] [options]
-i, --input DIR input directory (sorting mode)
-d, --detect FILE detect one media file; no sorting
-o, --output PATH output directory, or annotated file with
--detect --draw
-c, --config FILE config file (default: ./config.ini)
-r, --rule RULE label rule, e.g. "fge+!mge=ge"; repeatable;
when given, the config file is ignored
--default DIR target directory for files that match no rule
--draw draw boxes and labels into the annotated output
--copy copy instead of move
--no-preserve-path
ignore the source subdirectory structure
--rename-on-conflict
add a numeric suffix when the destination exists
--interval SEC video sampling interval (default: 2.0; 0 = every frame)
--score F confidence threshold (default: 0.25)
--nms F per-label NMS IoU threshold (default: 0.45)
--batch N inference batch size (default: 4)
--threads N ONNX intra-op threads (default: auto)
--model PATH external ONNX model (required if not embedded)
--resolution N model input size override for dynamic models
--hwaccel NAME hardware video decoding: auto (default), none,
or vaapi/cuda/qsv/vdpau/...; 'help' lists devices
--no-recursive only scan the top-level input directory
--include-hidden include dot-files/dot-directories
--early-stop stop decoding a file once the first label rule matches
--dry-run show decisions without changing files
-y, --yes skip fuzzy-label-rule confirmation
-v, --verbose verbose detection logging
-q, --quiet only errors, detections and summary
-h, --help show this help
--version show version
Examples:
# Sort in place, using ./config.ini.
./nnsort -i /media/downloads
# Sort into a separate output tree.
./nnsort -i /media/downloads -o /media/sorted
# Sort without a config file.
./nnsort -i /media/in -o /media/out \
-r "fge+!mge=./female" --default ./other
# Preview without changing anything.
./nnsort -i /media/downloads -o /media/sorted --dry-run -v
# Copy instead of move, sampling every second.
./nnsort -i /media/in -o /media/out --copy --interval 1
# Put every file directly in its target directory, ignoring subdirectories.
./nnsort -i /media/in -o /media/out --no-preserve-path
# Rename instead of skipping when the destination already exists.
./nnsort -i /media/in -o /media/out --rename-on-conflict
# Use the 640m model with its matching resolution.
./nnsort -i /media/in -o /media/out --model ./models/640m.onnx --resolution 640
# Prefer VAAPI hardware video decoding, or force pure software decoding.
./nnsort -i /media/in -o /media/out --hwaccel vaapi
./nnsort -i /media/in -o /media/out --hwaccel none
Detecting a single file
Detection mode runs the detector on one image or video and prints every label found. It never moves, copies, or changes the input file.
./nnsort --detect photo.jpg -c config.ini
./nnsort --detect clip.mp4 -c config.ini --interval 0.5
Detection mode uses the embedded model by default; pass --model PATH to use
an external model. [labels] is optional for detection mode.
Output example:
detections: /media/photo.jpg [image, 1 frame]
FEMALE_BREAST_EXPOSED 0.931 box 12.0,34.0 178.0,290.0
FACE_FEMALE 0.887 box 40.0,10.0 160.0,120.0
For videos, detections are aggregated across sampled frames:
detections: /media/clip.mp4 [video, 3 frames]
FEMALE_BREAST_EXPOSED 0.812 box 10.0,20.0 100.0,200.0 (2/3 frames)
Labels are listed by descending confidence. Boxes are in source pixel coordinates.
Annotating detections
Add --draw to write an annotated image or video:
# Writes photo.boxes.png next to the input
./nnsort --detect photo.jpg -c config.ini --draw
# Writes clip.boxes.mp4 next to the input
./nnsort --detect clip.mp4 -c config.ini --draw
# Explicit output path; the format follows the extension
./nnsort --detect clip.mp4 -c config.ini --draw -o /tmp/clip.boxes.mp4
- Images default to
<name>.boxes.png;.jpg,.jpeg,.png, and.bmpare supported for explicit output paths. - Videos default to
<name>.boxes.mp4, encoded with H.264 (libx264when available, otherwise MPEG-4). - The source file is never overwritten. An output path identical to the input is rejected.
- All NMS-surviving boxes are drawn (up to 128 highest-scoring boxes per frame), including multiple instances of the same label. Each box is labelled with the label name and confidence.
- Video frames between
--intervalsamples reuse the last detection result. Use--interval 0for per-frame detection, or a smaller interval when scene changes matter. - The primary audio stream is copied without re-encoding. If the selected
container cannot store that codec, the default output switches from MP4 to
MKV to preserve audio. An explicitly requested incompatible
.mp4output is an error. - Subtitles and data streams are not copied.
- Annotated videos are re-encoded, so video quality and file size differ from the source. Audio is not re-encoded.
- Detection mode processes frames sequentially;
--batchhas no effect there.
How sorting works
For every file, nnsort records which configured labels were detected in any
sampled frame. It then walks the [labels] rules from top to bottom and picks
the first rule that matches. A comma rule matches when at least one required
label appeared; a + rule matches only when every required label appeared.
Labels prefixed with ! must be absent. default is used only if no rule
matched.
Example:
- A file with
MALE_GENITALIA_EXPOSEDandFEMALE_BREAST_EXPOSEDgoes to./genitalia, because the first rule matches onMALE_GENITALIA_EXPOSED. - A file with both
FACE_FEMALEandFACE_MALEgoes to./faces. - A file with only
FACE_FEMALEdoes not match the+rule and falls through to the next matching rule, or to./other. - A file with only
FEMALE_BREAST_EXPOSEDgoes to./fb. - A file with
BUTTOCKS_EXPOSEDand noANUS_EXPOSEDgoes to./butts. - A file with
BUTTOCKS_EXPOSEDandANUS_EXPOSEDdoes not match theBUTTOCKS_EXPOSED + !ANUS_EXPOSEDrule and falls through to./other. - A file with only an unconfigured label goes to
./other. - A file with no detections goes to
./other. - If
defaultis omitted, unmatched files stay where they are.
Media handling
Supported image extensions:
jpg jpeg png webp bmp tif tiff gif
Supported video extensions:
mp4 mkv mov avi webm m4v mpg mpeg ts wmv flv
- Images use the first decoded frame. Animated GIF/WebP files are treated as images.
- Videos are decoded sequentially and sampled by presentation timestamp every
--intervalseconds. The first frame is always sampled. --interval 0processes every decoded frame.- Short scenes can be missed at large intervals; lower the interval if needed.
- Symlinks are skipped.
- Hidden files and directories are skipped unless
--include-hiddenis used. - The output directory and configured target directories are skipped when scanning, so already-sorted files are not processed again.
- Unreadable or corrupt files are reported. If no labels were detected, the file is left in place; if some frames were decoded and labels were found, it is sorted from those partial findings.
Hardware decoding
Video frames can be decoded through FFmpeg hardware devices:
--hwaccel auto # default: try a device, fall back to software
--hwaccel none # always use software decoding
--hwaccel vaapi # prefer VAAPI; fall back if unsupported
--hwaccel cuda # prefer CUDA/NVDEC; fall back if unsupported
--hwaccel help # list device types compiled into FFmpeg
On Linux, auto tries VAAPI, CUDA, QSV, and VDPAU in that order. A device is
only used when the decoder advertises support for the file's codec and profile.
If hardware setup fails, the file is decoded in software and the run continues.
The selected device is shown in --verbose output.
Hardware decoding applies to videos only. Still images and animated image files continue to use software decoding. Hardware frames are downloaded to system memory before the existing RGB conversion, so scaling, detection, and annotated output behave the same as with software decoding. ONNX inference remains CPU-only.
File operations
- Default action is
renamewithin the same filesystem. - Cross-filesystem moves fall back to copy + remove.
- Copies are written to a hidden temporary file in the destination directory and then atomically installed, so partial files are not left at the final path.
- Existing destination files are skipped. The source remains untouched.
- File permissions and modification timestamps are preserved on copied files.
--dry-runperforms detection but creates no directories and changes no files.
Early stop
By default the whole file is scanned, which gives complete verbose detection
logs. With --early-stop, decoding stops as soon as the first rule in
[labels] matches, because no later rule can override it. For a comma rule
that means any required label; for a + rule, all required labels must have
appeared. The destination is unchanged. Verbose logs for that file may omit
labels that appear later.
If the first rule contains a negated label, early stop is disabled for that run: absence can only be established after the whole file has been scanned.
This is especially useful for long videos where the highest-priority rule is common. It has no effect when no label rules are configured.
Output and exit status
Sorting mode reports scanned files, inferred frames, average decode and inference FPS, moved/copied/skipped files, unmatched files, errors, per-rule decisions, and elapsed time.
Detection mode prints the detected labels, average decode and inference FPS,
and, with --draw, the annotated output path.
The FPS metrics count all decoded source frames for decoding, including frames
skipped by --interval and hardware-frame download time, and measure inference
time across the complete detector call (preprocessing, ONNX Runtime inference,
and postprocessing).
Exit codes:
0: run completed (individual files may still have been skipped or reported as errors),1: fatal configuration/model/input/output error, or pipeline failure,2: command-line usage error.
Detection details
The implementation follows NudeNet 3.4 preprocessing:
- convert the decoded frame to RGB24,
- pad to a square at the right and bottom with black,
- resize to the model input size,
- normalize to
[0,1]and store as NCHWRGB.
Postprocessing:
- NudeNet output rows: 4 box coordinates followed by 18 class scores,
- default confidence threshold
0.25, - per-label NMS with default IoU
0.45, - per-label NMS is used deliberately so a detection of one configured label cannot suppress a different label that has higher priority in the config.
The sorter only needs label presence, so bounding boxes are used for verbose output and NMS, not for the final decision.
Limitations
- ONNX inference runs on the CPU. Hardware acceleration is available only for video decoding, and depends on the codec, profile, and installed drivers.
- Rotation/EXIF orientation metadata is not applied; detection runs on the stored frame orientation.
- Only the first frame of animated images is inspected.
- Annotated videos copy the primary audio stream only; subtitles and data streams are dropped.
- No archive/subtitle handling.
- Detection is only as good as the selected NudeNet model and threshold.
- Moving files is destructive by design; use
--dry-runor--copywhen trying a new configuration.
Attribution
NudeNet and its model weights are from notAI-tech/NudeNet, released under the MIT license. The detector labels and preprocessing/postprocessing behavior follow NudeNet 3.4.