-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.py
More file actions
43 lines (32 loc) · 1.29 KB
/
service.py
File metadata and controls
43 lines (32 loc) · 1.29 KB
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
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from PIL import Image
import io
from pathlib import Path
from inference import DogCatClassifier, MODEL_PATH
app = FastAPI(title="Dog vs Cat Classifier")
# Serve static files
STATIC_DIR = Path(__file__).parent / "static"
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
# Root route -> index.html
@app.get("/", response_class=HTMLResponse)
async def index():
index_path = STATIC_DIR / "index.html"
return FileResponse(index_path)
clf = DogCatClassifier(MODEL_PATH)
class PredictionResponse(BaseModel):
label: str
confidence: float
@app.post("/predict", response_model=PredictionResponse)
async def predict(file: UploadFile = File(...)):
if file.content_type not in ("image/jpeg", "image/png"):
raise HTTPException(status_code=400, detail="Only JPEG/PNG images are supported")
raw = await file.read()
try:
img = Image.open(io.BytesIO(raw)).convert("RGB")
except Exception:
raise HTTPException(status_code=400, detail="Could not decode image")
label, conf = clf.predict(img)
return PredictionResponse(label=label, confidence=conf)