Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from huggingface_hub import hf_hub_download
|
| 8 |
+
from imgutils.data import load_image
|
| 9 |
+
from imgutils.utils import open_onnx_model
|
| 10 |
+
|
| 11 |
+
_MODELS = [
|
| 12 |
+
('nsfwjs.onnx', 224),
|
| 13 |
+
('inception_v3.onnx', 299),
|
| 14 |
+
]
|
| 15 |
+
_MODEL_NAMES = [name for name, _ in _MODELS]
|
| 16 |
+
_DEFAULT_MODEL_NAME = _MODEL_NAMES[0]
|
| 17 |
+
_MODEL_TO_SIZE = dict(_MODELS)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@lru_cache()
|
| 21 |
+
def _onnx_model(name):
|
| 22 |
+
return open_onnx_model(hf_hub_download(
|
| 23 |
+
'deepghs/imgutils-models',
|
| 24 |
+
f'nsfw/{name}'
|
| 25 |
+
))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _image_preprocess(image, size: int = 224) -> np.ndarray:
|
| 29 |
+
image = load_image(image, mode='RGB').resize((size, size), Image.NEAREST)
|
| 30 |
+
return (np.array(image) / 255.0)[None, ...]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
_LABELS = ['drawings', 'hentai', 'neutral', 'porn', 'sexy']
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def predict(image, model_name):
|
| 37 |
+
input_ = _image_preprocess(image, _MODEL_TO_SIZE[model_name]).astype(np.float32)
|
| 38 |
+
output_, = _onnx_model(model_name).run(['dense_3'], {'input_1': input_})
|
| 39 |
+
return dict(zip(_LABELS, map(float, output_[0])))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == '__main__':
|
| 43 |
+
with gr.Blocks() as demo:
|
| 44 |
+
with gr.Row():
|
| 45 |
+
with gr.Column():
|
| 46 |
+
gr_input_image = gr.Image(type='pil', label='Original Image')
|
| 47 |
+
gr_model = gr.Dropdown(_MODEL_NAMES, value=_DEFAULT_MODEL_NAME, label='Model')
|
| 48 |
+
gr_btn_submit = gr.Button(value='Tagging', variant='primary')
|
| 49 |
+
|
| 50 |
+
with gr.Column():
|
| 51 |
+
gr_ratings = gr.Label(label='Ratings')
|
| 52 |
+
|
| 53 |
+
gr_btn_submit.click(
|
| 54 |
+
predict,
|
| 55 |
+
inputs=[gr_input_image, gr_model],
|
| 56 |
+
outputs=[gr_ratings],
|
| 57 |
+
)
|
| 58 |
+
demo.queue(os.cpu_count()).launch()
|