Spaces:
Runtime error
Runtime error
File size: 1,654 Bytes
5f739f3 | 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 60 61 | from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from transformers import pipeline
from PIL import Image
import requests
from io import BytesIO
app = FastAPI()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins for extension development
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load model
# Using the same model as in app.py
classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection")
class ImageRequest(BaseModel):
url: str
@app.post("/classify")
def classify_image(request: ImageRequest):
try:
# Fetch image
response = requests.get(request.url, timeout=10)
response.raise_for_status()
image = Image.open(BytesIO(response.content))
# Classify
predictions = classifier(image)
# Logic from app.py
top_prediction = max(predictions, key=lambda x: x['score'])
label = top_prediction['label']
score = top_prediction['score']
is_nsfw = label.lower() == 'nsfw'
return {
"is_nsfw": is_nsfw,
"score": score,
"label": label,
"predictions": predictions
}
except Exception as e:
# In a real app, logging would be better
print(f"Error processing image: {e}")
# Return safe default or error
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
|