Spaces:
Sleeping
Sleeping
Commit ·
7306a70
0
Parent(s):
Initial commit - Depression Detection API
Browse filesFiles changed (14)
- .gitattributesAdded+1
- .gitignoreAdded+28
- DockerfileAdded+29
- EfficientNet.ipynbAdded
- README.mdAdded+57
- README_DEPLOY.mdAdded+141
- face_detector.pyAdded+179
- main.pyAdded+126
- model.h5Added+3
- predictor.pyAdded+209
- render.yamlAdded+12
- requirements.txtAdded+7
- schemas.pyAdded+18
- test_model_load.pyAdded+33
1*.h5 filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# Virtual environmentvenv/env/.venv/
# IDE.idea/.vscode/*.swp*.swo
# Jupyter Notebook checkpoints.ipynb_checkpoints/
# Environment variables.env
# OS files.DS_StoreThumbs.db
# Logs*.log1234567891011121314151617181920212223242526272829# Use Python 3.10 slim imageFROM python:3.10-slim
# Set working directoryWORKDIR /app
# Install system dependencies for OpenCV and other librariesRUN apt-get update && apt-get install -y --no-install-recommends \ libgl1-mesa-glx \ libglib2.0-0 \ libsm6 \ libxrender1 \ libxext6 \ && rm -rf /var/lib/apt/lists/*
# Copy requirements first (for caching)COPY requirements.txt .
# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY . .
# Expose port 7860 (Hugging Face default)EXPOSE 7860
# Run the applicationCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# Depression Detection API
A FastAPI-based REST API for detecting depression from facial images using deep learning.
## Features
- **Face Detection**: Automatically detects and crops faces from uploaded images- **Depression Prediction**: Uses EfficientNetB0 model for binary classification- **Configurable Threshold**: Adjust prediction sensitivity via API parameter- **CORS Enabled**: Ready for mobile app integration
## API Endpoints
### `GET /health`Health check endpoint to verify API status.
### `POST /predict`Upload an image to get depression prediction.
**Parameters:**- `file`: Image file (JPEG, PNG, etc.)- `threshold`: Classification threshold (0.0-1.0, default: 0.5)
**Response:**```json{ "prediction": "depression" | "neutral", "confidence": 0.75}```
## Local Development
1. Install dependencies:```bashpip install -r requirements.txt```
2. Run the server:```bashuvicorn main:app --reload```
3. Open API docs at `http://localhost:8000/docs`
## Deployment to Render
1. Push this repository to GitHub2. Connect your GitHub repo to Render3. Render will automatically detect `render.yaml` and deploy
## Model Information
- **Architecture**: EfficientNetB0 (transfer learning)- **Input**: 224x224 RGB images- **Output**: Binary classification (depression vs neutral)- **Training Data**: Face images from CalmScope dataset123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# Deployment Guide for Depression Detection API
## 🚀 Option 1: Hugging Face Spaces (Recommended - FREE)
### Step 1: Create a Hugging Face Account1. Go to [huggingface.co](https://huggingface.co)2. Click "Sign Up" and create a free account3. Verify your email
### Step 2: Create a New Space1. Go to [huggingface.co/new-space](https://huggingface.co/new-space)2. Fill in the details: - **Space name**: `depression-detection-api` - **License**: Choose appropriate license (e.g., MIT) - **SDK**: Select **Docker** - **Hardware**: Keep **CPU basic - Free**3. Click "Create Space"
### Step 3: Upload Your FilesYou can either:
**Option A: Using Git (Recommended)**```bash# Clone your new spacegit clone https://huggingface.co/spaces/YOUR_USERNAME/depression-detection-api
# Copy your files to the cloned directory# Then push:cd depression-detection-apigit add .git commit -m "Initial deployment"git push```
**Option B: Manual Upload**1. Go to your Space's "Files" tab2. Upload these files: - `main.py` - `predictor.py` - `face_detector.py` - `schemas.py` - `requirements.txt` - `Dockerfile` - `model.h5`
### Step 4: Wait for Build- Hugging Face will automatically build and deploy your app- This may take 5-10 minutes for the first build- Your API will be available at: `https://YOUR_USERNAME-depression-detection-api.hf.space`
### Step 5: Test Your API```bash# Health checkcurl https://YOUR_USERNAME-depression-detection-api.hf.space/health
# Prediction (replace with your image)curl -X POST "https://YOUR_USERNAME-depression-detection-api.hf.space/predict" \ -F "file=@test_image.jpg"```
---
## 🔧 Option 2: Render (Alternative - FREE)
### Step 1: Push to GitHub1. Create a new GitHub repository2. Push your code (including `render.yaml`)
### Step 2: Deploy on Render1. Go to [render.com](https://render.com) and sign up2. Click "New" → "Web Service"3. Connect your GitHub repository4. Render will auto-detect `render.yaml`5. Click "Create Web Service"
### Important Notes for Render:- ⚠️ Free tier spins down after 15 minutes of inactivity- ⚠️ First request after spin-down takes 30-60 seconds (cold start)- ⚠️ May have issues with large model files
---
## 📱 Using the API in Your Mobile App
### API Endpoints
| Endpoint | Method | Description ||----------|--------|-------------|| `/` | GET | API info || `/health` | GET | Health check || `/predict` | POST | Predict depression from image || `/docs` | GET | Swagger UI documentation |
### Example API Call (Android/Kotlin)```kotlin// Using Retrofitinterface DepressionApi { @Multipart @POST("predict") suspend fun predict( @Part file: MultipartBody.Part, @Query("threshold") threshold: Float = 0.5f ): PredictionResponse}
data class PredictionResponse( val prediction: String, // "depression" or "neutral" val confidence: Float // 0.0 to 1.0)```
### Example API Call (React Native / JavaScript)```javascriptconst formData = new FormData();formData.append('file', { uri: imageUri, type: 'image/jpeg', name: 'photo.jpg',});
const response = await fetch('https://YOUR-API-URL/predict', { method: 'POST', body: formData, headers: { 'Content-Type': 'multipart/form-data', },});
const result = await response.json();console.log(result.prediction, result.confidence);```
---
## 🔗 Your API URL
After deployment, your API will be available at:- **Hugging Face**: `https://YOUR_USERNAME-depression-detection-api.hf.space`- **Render**: `https://depression-detection-api.onrender.com`
Replace the placeholder URL in your mobile app with your actual deployed URL.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179import cv2import numpy as npfrom typing import Optional, Tuple, List
class FaceDetector: """Face detection utility with multiple detection strategies.""" def __init__(self): """Initialize the face detector with multiple Haar Cascade classifiers.""" # Primary detector - frontal face self.face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' ) # Alternative detector - frontal face alt self.face_cascade_alt = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml' ) # Another alternative - frontal face alt2 self.face_cascade_alt2 = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml' ) def _detect_with_cascade( self, gray: np.ndarray, cascade: cv2.CascadeClassifier, scale_factor: float = 1.1, min_neighbors: int = 3, min_size: Tuple[int, int] = (20, 20) ) -> List: """Detect faces using a specific cascade classifier.""" try: faces = cascade.detectMultiScale( gray, scaleFactor=scale_factor, minNeighbors=min_neighbors, minSize=min_size, flags=cv2.CASCADE_SCALE_IMAGE ) return list(faces) if len(faces) > 0 else [] except Exception: return [] def detect_and_crop_face( self, image: np.ndarray, target_size: Tuple[int, int] = (224, 224), padding: float = 0.2 ) -> Optional[np.ndarray]: """ Detect face in image and crop it with padding. Uses multiple detection strategies for robustness. Args: image: Input image as numpy array (BGR format from OpenCV) target_size: Target size for the cropped face (width, height) padding: Padding ratio to add around the detected face Returns: Cropped and resized face image, or None if no face detected """ if image is None or image.size == 0: print("Warning: Empty or invalid image received") return None # Convert to grayscale try: if len(image.shape) == 2: gray = image else: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) except Exception as e: print(f"Warning: Failed to convert to grayscale: {e}") return None # Enhance contrast for better detection gray = cv2.equalizeHist(gray) faces = [] # Strategy 1: Primary cascade with standard parameters faces = self._detect_with_cascade(gray, self.face_cascade, 1.1, 5, (30, 30)) # Strategy 2: Primary cascade with more lenient parameters if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade, 1.05, 3, (20, 20)) # Strategy 3: Alt cascade if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade_alt, 1.1, 3, (20, 20)) # Strategy 4: Alt2 cascade if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade_alt2, 1.1, 3, (20, 20)) # Strategy 5: Very lenient detection if len(faces) == 0: faces = self._detect_with_cascade(gray, self.face_cascade, 1.02, 2, (15, 15)) # Strategy 6: Try with different image sizes if len(faces) == 0: # Try with scaled up image scale = 1.5 scaled = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) faces = self._detect_with_cascade(scaled, self.face_cascade, 1.1, 3, (30, 30)) if len(faces) > 0: # Scale coordinates back faces = [(int(x/scale), int(y/scale), int(w/scale), int(h/scale)) for (x, y, w, h) in faces] # Strategy 7: If still no face, use the entire image as the face region # This is a fallback for cases where face detection fails but user insists image has a face if len(faces) == 0: print("Warning: No face detected with any strategy. Using center crop as fallback.") h, w = image.shape[:2] # Use center 70% of the image margin_w = int(w * 0.15) margin_h = int(h * 0.15) face_crop = image[margin_h:h-margin_h, margin_w:w-margin_w] if face_crop.size > 0: face_resized = cv2.resize(face_crop, target_size, interpolation=cv2.INTER_AREA) if len(face_resized.shape) == 3: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_BGR2RGB) else: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_GRAY2RGB) return face_rgb return None # Get the largest face x, y, w, h = max(faces, key=lambda f: f[2] * f[3]) # Add padding pad_w = int(w * padding) pad_h = int(h * padding) img_h, img_w = image.shape[:2] x1 = max(0, x - pad_w) y1 = max(0, y - pad_h) x2 = min(img_w, x + w + pad_w) y2 = min(img_h, y + h + pad_h) face_crop = image[y1:y2, x1:x2] if face_crop.size == 0: return None face_resized = cv2.resize(face_crop, target_size, interpolation=cv2.INTER_AREA) # Convert to RGB if len(face_resized.shape) == 3: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_BGR2RGB) else: face_rgb = cv2.cvtColor(face_resized, cv2.COLOR_GRAY2RGB) return face_rgb def detect_faces_count(self, image: np.ndarray) -> int: """ Count number of faces detected in image. Args: image: Input image as numpy array Returns: Number of faces detected """ try: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) faces = self._detect_with_cascade(gray, self.face_cascade, 1.1, 3, (20, 20)) return len(faces) except Exception: return 0
face_detector = FaceDetector()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import ioimport cv2import numpy as npfrom fastapi import FastAPI, File, UploadFile, Query, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom PIL import Image
from schemas import PredictionResponse, HealthResponse, ErrorResponsefrom face_detector import face_detectorfrom 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)123version https://git-lfs.github.com/spec/v1oid sha256:4bccf6b1c6b00a52f05898d2b40fc6dee371d656441fb5b67847e110245f4edesize 46992968123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209import osimport numpy as npimport tensorflow as tffrom tensorflow.keras.applications.efficientnet import preprocess_inputfrom typing import Tuple, Optional
class DepressionPredictor: """Depression detection predictor using EfficientNetB0 model.""" def __init__(self, model_path: str = "model.h5"): """ Initialize the predictor with the trained model. Args: model_path: Path to the trained model file """ self.model: Optional[tf.keras.Model] = None self.model_path = model_path self.input_size = (224, 224) self.class_names = ["depression", "neutral"] self._load_model() def _load_model(self) -> None: """Load the trained model from disk.""" try: if os.path.exists(self.model_path): print(f"Attempting to load model from {self.model_path}...") # Create a DTypePolicy stub class for Keras 3.x compatibility # This handles models saved with newer Keras versions class DTypePolicy: """Stub for Keras 3.x DTypePolicy to enable loading in Keras 2.x""" def __init__(self, name='float32', **kwargs): self.name = name self._name = name def __repr__(self): return f"DTypePolicy('{self.name}')" @classmethod def from_config(cls, config): if isinstance(config, dict): return cls(name=config.get('name', 'float32')) return cls(name='float32') # Custom InputLayer to handle batch_shape -> shape conversion class CompatibleInputLayer(tf.keras.layers.InputLayer): def __init__(self, **kwargs): if 'batch_shape' in kwargs: batch_shape = kwargs.pop('batch_shape') if batch_shape is not None: kwargs['input_shape'] = batch_shape[1:] # Handle DTypePolicy from newer Keras if 'dtype' in kwargs: dtype_val = kwargs['dtype'] if isinstance(dtype_val, dict): kwargs['dtype'] = dtype_val.get('config', {}).get('name', 'float32') elif hasattr(dtype_val, 'name'): kwargs['dtype'] = dtype_val.name super().__init__(**kwargs) # Custom Rescaling layer for Keras 3.x compatibility class CompatibleRescaling(tf.keras.layers.Rescaling): def __init__(self, scale, offset=0.0, **kwargs): kwargs.pop('dtype', None) super().__init__(scale=scale, offset=offset, **kwargs) # Custom Dense layer to handle dtype serialization class CompatibleDense(tf.keras.layers.Dense): def __init__(self, units, **kwargs): if 'dtype' in kwargs: dtype_val = kwargs['dtype'] if isinstance(dtype_val, dict): kwargs['dtype'] = dtype_val.get('config', {}).get('name', 'float32') elif hasattr(dtype_val, 'name'): kwargs['dtype'] = dtype_val.name super().__init__(units, **kwargs) # Build custom objects dict custom_objects = { 'InputLayer': CompatibleInputLayer, 'Rescaling': CompatibleRescaling, 'Dense': CompatibleDense, 'DTypePolicy': DTypePolicy, } # Try different loading strategies model_loaded = False # Strategy 1: Direct load with custom objects try: print("Strategy 1: Loading with custom objects...") self.model = tf.keras.models.load_model( self.model_path, custom_objects=custom_objects, compile=False ) model_loaded = True print("Strategy 1 successful!") except Exception as e1: print(f"Strategy 1 failed: {e1}") # Strategy 2: Load weights only into rebuilt architecture try: print("Strategy 2: Rebuilding EfficientNetB0 architecture and loading weights...") self.model = self._rebuild_model_architecture() self.model.load_weights(self.model_path, by_name=True, skip_mismatch=True) model_loaded = True print("Strategy 2 successful!") except Exception as e2: print(f"Strategy 2 failed: {e2}") if model_loaded: # Recompile the model self.model.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) print(f"Model loaded and compiled successfully from {self.model_path}") else: print("All loading strategies failed!") self.model = None else: print(f"Warning: Model file not found at {self.model_path}") self.model = None except Exception as e: print(f"Exception encountered: {e}") import traceback traceback.print_exc() self.model = None def _rebuild_model_architecture(self) -> tf.keras.Model: """Rebuild the EfficientNetB0 model architecture for weight loading.""" from tensorflow.keras import layers, Model # Create the same architecture as in the training notebook inputs = layers.Input(shape=(224, 224, 3), name='input') base_model = tf.keras.applications.EfficientNetB0( include_top=False, weights='imagenet', input_tensor=inputs ) x = layers.GlobalAveragePooling2D(name='global_avg_pool')(base_model.output) x = layers.Dropout(0.2, name='dropout1')(x) x = layers.Dense(256, activation='relu', name='fc1')(x) x = layers.Dropout(0.2, name='dropout2')(x) outputs = layers.Dense(1, activation='sigmoid', name='output')(x) model = Model(inputs, outputs, name='EfficientNetB0_depression') return model def is_model_loaded(self) -> bool: """Check if the model is loaded successfully.""" return self.model is not None def preprocess_image(self, image: np.ndarray) -> np.ndarray: """ Preprocess image for model inference. Args: image: Input image as numpy array (RGB format, 224x224) Returns: Preprocessed image ready for model inference """ img = image.astype(np.float32) img = preprocess_input(img) img = np.expand_dims(img, axis=0) return img def predict(self, image: np.ndarray, threshold: float = 0.5) -> Tuple[str, float]: """ Predict depression status from face image. Args: image: Preprocessed face image (RGB, 224x224) threshold: Classification threshold (default: 0.5) Returns: Tuple of (prediction_label, confidence_score) Raises: RuntimeError: If model is not loaded """ if not self.is_model_loaded(): raise RuntimeError("Model is not loaded") preprocessed = self.preprocess_image(image) raw_prediction = self.model.predict(preprocessed, verbose=0)[0][0] if raw_prediction >= threshold: prediction = "neutral" confidence = float(raw_prediction) else: prediction = "depression" confidence = float(1 - raw_prediction) return prediction, confidence
predictor = DepressionPredictor()123456789101112services: - type: web name: depression-detection-api env: python region: oregon plan: free buildCommand: pip install -r requirements.txt startCommand: uvicorn main:app --host 0.0.0.0 --port $PORT healthCheckPath: /health envVars: - key: PYTHON_VERSION value: 3.10.121234567fastapi==0.104.1uvicorn[standard]==0.24.0python-multipart==0.0.6tensorflow==2.15.0opencv-python-headless==4.8.1.78numpy==1.26.2pillow==10.1.0123456789101112131415161718from pydantic import BaseModel, Field
class PredictionResponse(BaseModel): """Response model for depression prediction endpoint.""" prediction: str = Field(..., description="Prediction result: 'depression' or 'neutral'") confidence: float = Field(..., description="Confidence score between 0 and 1", ge=0.0, le=1.0)
class HealthResponse(BaseModel): """Response model for health check endpoint.""" status: str = Field(..., description="Health status of the API") model_loaded: bool = Field(..., description="Whether the ML model is loaded successfully")
class ErrorResponse(BaseModel): """Response model for error responses.""" detail: str = Field(..., description="Error message details")123456789101112131415161718192021222324252627282930313233import osimport tensorflow as tf
model_path = "model.h5"
print(f"TensorFlow version: {tf.__version__}")print(f"Keras (bundled with TensorFlow): {tf.__version__}")print(f"Model file exists: {os.path.exists(model_path)}")
try: # Custom InputLayer to handle batch_shape -> shape conversion class CompatibleInputLayer(tf.keras.layers.InputLayer): def __init__(self, **kwargs): print(f"InputLayer kwargs: {kwargs}") if 'batch_shape' in kwargs: batch_shape = kwargs.pop('batch_shape') if batch_shape is not None: kwargs['input_shape'] = batch_shape[1:] super().__init__(**kwargs) custom_objects = {'InputLayer': CompatibleInputLayer} model = tf.keras.models.load_model( model_path, custom_objects=custom_objects, compile=False ) print("Model loaded successfully!") print(f"Model summary:") model.summary()except Exception as e: print(f"Error loading model: {e}") import traceback traceback.print_exc().gitattributesAdded+1
.gitignoreAdded+28
DockerfileAdded+29
EfficientNet.ipynbAdded
README.mdAdded+57
README_DEPLOY.mdAdded+141
face_detector.pyAdded+179
main.pyAdded+126
model.h5Added+3
predictor.pyAdded+209
render.yamlAdded+12
requirements.txtAdded+7
schemas.pyAdded+18
test_model_load.pyAdded+33