File size: 1,853 Bytes
15c813b |
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, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import io
from transformers import pipeline
app = FastAPI()
# Allow CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load AI Detection Model
# We use a pre-trained model from Hugging Face
# 'Organika/sdxl-detector' is specialized for Stable Diffusion detection
print("Loading AI Model...")
classifier = pipeline("image-classification", model="Organika/sdxl-detector")
print("Model Loaded!")
@app.post("/analyze")
async def analyze_media(file: UploadFile = File(...)):
try:
contents = await file.read()
image = Image.open(io.BytesIO(contents))
# Run Inference
results = classifier(image)
# results is a list like [{'label': 'artificial', 'score': 0.99}, {'label': 'human', 'score': 0.01}]
# Find the 'artificial' or 'AI' score
ai_score = 0.0
for r in results:
label = r['label'].lower()
if 'artificial' in label or 'ai' in label:
ai_score = r['score']
break
if 'human' in label or 'real' in label:
# If we found human score, AI score is 1 - human
ai_score = 1.0 - r['score']
is_ai = ai_score > 0.5
return {
"filename": file.filename,
"is_ai": is_ai,
"confidence": round(ai_score * 100, 2), # Return 0-100
"details": results
}
except Exception as e:
print(f"Error: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/")
def read_root():
return {"status": "AI Detector Neural Network is Running"}
|