Spaces:
Sleeping
Sleeping
Download main.py from KnowingFly/depression-detection-api: direct link, hf CLI and curl.
- Browser
- Download file 3.73 kB
-
https://huggingface.co/spaces/KnowingFly/depression-detection-api/resolve/main/main.py
- Command line
-
hf download hf://spaces/KnowingFly/depression-detection-api/main.py
-
curl -L -o main.py https://huggingface.co/spaces/KnowingFly/depression-detection-api/resolve/main/main.py
3.73 kB
| 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=["*"], | |
| ) | |
| async def root(): | |
| """Root endpoint with API information.""" | |
| return { | |
| "message": "Depression Detection API", | |
| "version": "1.0.0", | |
| "docs": "/docs", | |
| } | |
| 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() | |
| ) | |
| 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) | |