Spaces:
Sleeping
Sleeping
File size: 3,730 Bytes
7306a70 | 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | import io
import cv2
import numpy as np
from fastapi import FastAPI, File, UploadFile, Query, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
from schemas import PredictionResponse, HealthResponse, ErrorResponse
from face_detector import face_detector
from predictor import predictor
app = FastAPI(
title="Depression Detection API",
description="API for detecting depression from facial images using machine learning",
version="1.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/", tags=["Root"])
async def root():
"""Root endpoint with API information."""
return {
"message": "Depression Detection API",
"version": "1.0.0",
"docs": "/docs",
}
@app.get("/health", response_model=HealthResponse, tags=["Health"])
async def health_check():
"""Health check endpoint to verify API and model status."""
return HealthResponse(
status="healthy" if predictor.is_model_loaded() else "degraded",
model_loaded=predictor.is_model_loaded()
)
@app.post(
"/predict",
response_model=PredictionResponse,
responses={
400: {"model": ErrorResponse, "description": "Bad Request - No face detected or invalid image"},
422: {"model": ErrorResponse, "description": "Validation Error"},
500: {"model": ErrorResponse, "description": "Internal Server Error"},
},
tags=["Prediction"]
)
async def predict_depression(
file: UploadFile = File(..., description="Image file containing a face"),
threshold: float = Query(
default=0.5,
ge=0.0,
le=1.0,
description="Classification threshold (0.0-1.0). Higher values favor 'neutral' predictions."
)
):
"""
Predict depression status from a facial image.
- **file**: Image file (JPEG, PNG, etc.) containing a face
- **threshold**: Classification threshold (default: 0.5)
Returns prediction result ('depression' or 'neutral') with confidence score.
"""
if not predictor.is_model_loaded():
raise HTTPException(
status_code=500,
detail="Model is not loaded. Please check server logs."
)
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(
status_code=400,
detail="Invalid file type. Please upload an image file."
)
try:
contents = await file.read()
pil_image = Image.open(io.BytesIO(contents))
if pil_image.mode != "RGB":
pil_image = pil_image.convert("RGB")
cv_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"Failed to process image: {str(e)}"
)
face_image = face_detector.detect_and_crop_face(cv_image)
if face_image is None:
raise HTTPException(
status_code=400,
detail="No face detected in the image. Please upload an image with a clearly visible face."
)
try:
prediction, confidence = predictor.predict(face_image, threshold=threshold)
return PredictionResponse(
prediction=prediction,
confidence=round(confidence, 4)
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Prediction failed: {str(e)}"
)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|