f
gcw_pCMO8DfP/nsfw_image_detector
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

NSFW Image Detector — 昇腾 Ascend NPU 适配版

Freepik/nsfw_image_detector 是一个 NSFW(Not-Safe-For-Work)图像风险检测模型。本仓库为 昇腾 Ascend NPU (torch_npu) 适配版,全流程无 CUDA,可在 Ascend910 上以 bf16 精度完成单图 4 分类风险判定。

  • 架构:TimmWrapperForImageClassification(transformers 内置 timm wrapper)
  • Backbone:timm/eva02_base_patch14_448(EVA-02 Base, 448×448 输入)
  • 分类:4 类 —— neutral / low / medium / high
  • 输出:4 类概率 + NSFW 风险评分 risk = P(medium)+P(high),risk ≥ 0.5 判定为 NSFW
  • 预处理:pretrained_cfg 手动归一化(bicubic 缩放 448×448 squash,无 crop),mean/std = [0.48145466, 0.4578275, 0.40821073] / [0.26862954, 0.26130258, 0.27577711]

环境要求

  • Python 3.11+,昇腾 NPU(Ascend910)+ torch_npu 2.9 + CANN
  • 依赖:torch torch_npu transformers timm fastapi uvicorn python-multipart safetensors pillow numpy

快速开始

# 命令行单图推理
python3 inference.py --img sample_input.png

# 启动 FastAPI 服务 (根路径为上传表单, POST /predict 返回推理 JSON)
python3 inference.py --server            # 默认端口 8000
python3 inference.py --server --port 8001 # 指定端口

命令行参数

参数说明
--img输入图片路径 (必需)
--server启动 FastAPI Web 服务
--port服务端口 (仅 --server 模式, 默认 8000)

输出格式

{
  "model": "Freepik/nsfw_image_detector",
  "pipeline": "image-classification",
  "device": "npu:0",
  "labels": ["neutral", "low", "medium", "high"],
  "probabilities": {
    "neutral": 0.997143,
    "low": 0.002382,
    "medium": 0.000146,
    "high": 0.000329
  },
  "predicted_label": "neutral",
  "predicted_score": 0.997143,
  "nsfw_risk_score": 0.000475,
  "nsfw_threshold": 0.5,
  "verdict": "SAFE",
  "inference_time_s": 0.154
}

模型权重

权重从 GitCode 镜像自动下载,缓存到 ./model_weights/(symlink 到共享缓存),优先复用本地缓存;缺失 preprocessor_config.json 时使用 config.json 中 pretrained_cfg 的 mean/std 手动归一化,无需额外预处理文件。

昇腾 NPU 验证

  • 设备:npu:0(torch.npu.is_available()=True, Ascend910 ×2)
  • 推理:单图 4 分类,bf16,batch=1,约 0.15s
  • 无任何 CUDA 设备调用代码

截图

NPU 环境部署与任务启动

agent_workflow

CLI 单图推理成功 (device=npu:0)

npu_device_call

FastAPI /predict 返回 JSON

model_result

项目结构

nsfw_image_detector/
├── inference.py        # 主推理脚本 (CLI + FastAPI 双模式)
├── sample_input.png    # 示例输入图像
├── README.md
├── model_weights/      # 权重缓存 (symlink 到共享缓存)
└── assets/             # 截图 + 原始日志
    ├── agent_workflow.png
    ├── npu_device_call.png
    ├── model_result.png
    └── _logs/