Upload 3 files
Browse files- Dockerfile +13 -0
- main.py +44 -0
- requirements.txt +5 -0
Dockerfile
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.11-slim
|
2 |
+
|
3 |
+
# Install dependencies
|
4 |
+
RUN pip install --no-cache-dir fastapi uvicorn transformers torch Pillow
|
5 |
+
|
6 |
+
# Create app directory
|
7 |
+
WORKDIR /app
|
8 |
+
|
9 |
+
# Copy everything
|
10 |
+
COPY . .
|
11 |
+
|
12 |
+
# Run FastAPI
|
13 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
main.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.environ["HF_HOME"] = "/tmp/huggingface" # Allow caching on Hugging Face Spaces
|
3 |
+
|
4 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
6 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
7 |
+
from PIL import Image
|
8 |
+
import torch
|
9 |
+
import io
|
10 |
+
|
11 |
+
app = FastAPI()
|
12 |
+
app.add_middleware(
|
13 |
+
CORSMiddleware,
|
14 |
+
allow_origins=["*"],
|
15 |
+
allow_methods=["*"],
|
16 |
+
allow_headers=["*"],
|
17 |
+
)
|
18 |
+
|
19 |
+
# Load model + processor
|
20 |
+
processor = AutoImageProcessor.from_pretrained("Organika/sdxl-detector")
|
21 |
+
model = AutoModelForImageClassification.from_pretrained("Organika/sdxl-detector")
|
22 |
+
|
23 |
+
@app.post("/analyze")
|
24 |
+
async def analyze(file: UploadFile = File(...)):
|
25 |
+
img_bytes = await file.read()
|
26 |
+
|
27 |
+
try:
|
28 |
+
image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
29 |
+
except:
|
30 |
+
raise HTTPException(status_code=400, detail="Invalid image file.")
|
31 |
+
|
32 |
+
inputs = processor(images=image, return_tensors="pt")
|
33 |
+
with torch.no_grad():
|
34 |
+
logits = model(**inputs).logits
|
35 |
+
probs = torch.nn.functional.softmax(logits, dim=1)[0]
|
36 |
+
|
37 |
+
labels = model.config.id2label
|
38 |
+
scores = {labels[i]: float(probs[i]) for i in range(len(probs))}
|
39 |
+
|
40 |
+
return {
|
41 |
+
"result": max(scores, key=scores.get),
|
42 |
+
"confidence": max(scores.values()),
|
43 |
+
"scores": scores,
|
44 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi
|
2 |
+
uvicorn
|
3 |
+
transformers
|
4 |
+
torch
|
5 |
+
Pillow
|