|
import streamlit as st |
|
from transformers import ViTImageProcessor, AutoModelForImageClassification |
|
from PIL import Image |
|
import requests |
|
from io import BytesIO |
|
import json |
|
|
|
|
|
processor = ViTImageProcessor.from_pretrained('AdamCodd/vit-base-nsfw-detector') |
|
model = AutoModelForImageClassification.from_pretrained('AdamCodd/vit-base-nsfw-detector') |
|
|
|
|
|
def predict_image(image): |
|
try: |
|
|
|
inputs = processor(images=image, return_tensors="pt") |
|
outputs = model(**inputs) |
|
logits = outputs.logits |
|
|
|
|
|
predicted_class_idx = logits.argmax(-1).item() |
|
predicted_label = model.config.id2label[predicted_class_idx] |
|
|
|
return predicted_label |
|
except Exception as e: |
|
return str(e) |
|
|
|
|
|
st.title("NSFW Image Classifier") |
|
|
|
|
|
image_url_ui = st.text_input("Enter Image URL", placeholder="Enter image URL here") |
|
|
|
|
|
@st.experimental_singleton |
|
def api_endpoint(): |
|
if request.method == 'POST': |
|
data = request.json |
|
if 'image_url' in data: |
|
try: |
|
image_url = data['image_url'] |
|
|
|
response = requests.get(image_url) |
|
image = Image.open(BytesIO(response.content)) |
|
|
|
|
|
prediction = predict_image(image) |
|
return json.dumps({'predicted_class': prediction}) |
|
except Exception as e: |
|
return json.dumps({'error': str(e)}), 500 |
|
else: |
|
return json.dumps({'error': 'Missing "image_url" in request body'}), 400 |
|
else: |
|
return json.dumps({'error': 'Only POST requests are allowed'}), 405 |
|
|
|
st.experimental_next_router(api_endpoint) |
|
|
|
if image_url_ui: |
|
try: |
|
|
|
response = requests.get(image_url_ui) |
|
image = Image.open(BytesIO(response.content)) |
|
st.image(image, caption='Image from URL', use_column_width=True) |
|
st.write("") |
|
st.write("Classifying...") |
|
|
|
|
|
prediction = predict_image(image) |
|
st.write(f"Predicted Class: {prediction}") |
|
except Exception as e: |
|
st.write(f"Error: {e}") |
|
|
|
|
|
space_url = st.session_state.get('huggingface_space_url') |
|
if space_url: |
|
api_endpoint_url = f"{space_url}/api/classify" |
|
st.write(f"You can also use this API endpoint to classify images:") |
|
st.write(f"```curl") |
|
st.write(f"curl -X POST -H 'Content-Type: application/json' -d '{{ \"image_url\": \"https://example.jpg\" }}' {api_endpoint_url}") |
|
st.write(f"```") |
|
st.write(f"This will return the predicted class in JSON format.") |