Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import ViTImageProcessor, AutoModelForImageClassification
|
3 |
+
from PIL import Image
|
4 |
+
import requests
|
5 |
+
|
6 |
+
# Load the model and processor
|
7 |
+
processor = ViTImageProcessor.from_pretrained('yeftakun/vit-base-nsfw-detector')
|
8 |
+
model = AutoModelForImageClassification.from_pretrained('yeftakun/vit-base-nsfw-detector')
|
9 |
+
|
10 |
+
# Define prediction function
|
11 |
+
def predict_image(image_url):
|
12 |
+
try:
|
13 |
+
# Load image from URL
|
14 |
+
image = Image.open(requests.get(image_url, stream=True).raw)
|
15 |
+
|
16 |
+
# Process the image and make prediction
|
17 |
+
inputs = processor(images=image, return_tensors="pt")
|
18 |
+
outputs = model(**inputs)
|
19 |
+
logits = outputs.logits
|
20 |
+
|
21 |
+
# Get predicted class
|
22 |
+
predicted_class_idx = logits.argmax(-1).item()
|
23 |
+
predicted_label = model.config.id2label[predicted_class_idx]
|
24 |
+
|
25 |
+
return predicted_label
|
26 |
+
except Exception as e:
|
27 |
+
return str(e)
|
28 |
+
|
29 |
+
# Create Gradio interface
|
30 |
+
iface = gr.Interface(
|
31 |
+
fn=predict_image,
|
32 |
+
inputs=gr.inputs.Textbox(label="Image URL"),
|
33 |
+
outputs=gr.outputs.Textbox(label="Predicted Class"),
|
34 |
+
title="NSFW Image Classifier"
|
35 |
+
)
|
36 |
+
|
37 |
+
# Launch the interface
|
38 |
+
iface.launch()
|