OwenElliott
commited on
Commit
•
ec7d005
1
Parent(s):
ce676a9
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from urllib.request import urlopen
|
3 |
+
from PIL import Image
|
4 |
+
import timm
|
5 |
+
import torch
|
6 |
+
|
7 |
+
# Load the model
|
8 |
+
model = timm.create_model("hf_hub:Marqo/nsfw-image-detection-384", pretrained=True)
|
9 |
+
model = model.eval()
|
10 |
+
|
11 |
+
# Prepare the data transformation
|
12 |
+
data_config = timm.data.resolve_model_data_config(model)
|
13 |
+
transforms = timm.data.create_transform(**data_config, is_training=False)
|
14 |
+
|
15 |
+
# Prediction function
|
16 |
+
def predict(image):
|
17 |
+
with torch.no_grad():
|
18 |
+
# Transform the image
|
19 |
+
input_tensor = transforms(image).unsqueeze(0)
|
20 |
+
# Run the model
|
21 |
+
output = model(input_tensor).softmax(dim=-1).cpu()
|
22 |
+
# Get class names
|
23 |
+
class_names = model.pretrained_cfg["label_names"]
|
24 |
+
# Create the result dictionary
|
25 |
+
result = {class_names[i]: float(output[0, i]) for i in range(len(class_names))}
|
26 |
+
return result
|
27 |
+
|
28 |
+
# Gradio interface
|
29 |
+
interface = gr.Interface(
|
30 |
+
fn=predict,
|
31 |
+
inputs=gr.Image(type="pil"),
|
32 |
+
outputs=gr.Label(num_top_classes=3),
|
33 |
+
title="NSFW Image Detection",
|
34 |
+
description="Upload an image to detect if it is NSFW or Safe for Work."
|
35 |
+
)
|
36 |
+
|
37 |
+
if __name__ == "__main__":
|
38 |
+
interface.launch()
|