File size: 1,694 Bytes
9469fcd
 
 
 
 
 
 
 
 
 
6823fd7
 
 
 
 
 
 
 
9469fcd
 
6823fd7
9469fcd
 
6823fd7
9469fcd
 
 
 
 
 
 
 
 
 
 
6823fd7
 
 
9469fcd
 
 
 
 
 
 
 
6823fd7
9469fcd
 
 
 
 
 
 
6823fd7
9469fcd
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import os
from functools import lru_cache

import gradio as gr
import numpy as np
from PIL import Image
from huggingface_hub import hf_hub_download
from imgutils.data import load_image
from imgutils.utils import open_onnx_model

_MODELS = [
    ('nsfwjs.onnx', 224),
    ('inception_v3.onnx', 299),
]
_MODEL_NAMES = [name for name, _ in _MODELS]
_DEFAULT_MODEL_NAME = _MODEL_NAMES[0]
_MODEL_TO_SIZE = dict(_MODELS)


@lru_cache()
def _onnx_model(name):
    return open_onnx_model(hf_hub_download(
        'deepghs/imgutils-models',
        f'nsfw/{name}'
    ))


def _image_preprocess(image, size: int = 224) -> np.ndarray:
    image = load_image(image, mode='RGB').resize((size, size), Image.NEAREST)
    return (np.array(image) / 255.0)[None, ...]


_LABELS = ['drawings', 'hentai', 'neutral', 'porn', 'sexy']


def predict(image, model_name):
    input_ = _image_preprocess(image, _MODEL_TO_SIZE[model_name]).astype(np.float32)
    output_, = _onnx_model(model_name).run(['dense_3'], {'input_1': input_})
    return dict(zip(_LABELS, map(float, output_[0])))


if __name__ == '__main__':
    with gr.Blocks() as demo:
        with gr.Row():
            with gr.Column():
                gr_input_image = gr.Image(type='pil', label='Original Image')
                gr_model = gr.Dropdown(_MODEL_NAMES, value=_DEFAULT_MODEL_NAME, label='Model')
                gr_btn_submit = gr.Button(value='Tagging', variant='primary')

            with gr.Column():
                gr_ratings = gr.Label(label='Ratings')

        gr_btn_submit.click(
            predict,
            inputs=[gr_input_image, gr_model],
            outputs=[gr_ratings],
        )
    demo.queue(os.cpu_count()).launch()