Back to Projects

Project

PHQ-9 DSM-5 Based Mental Health Predictor

A machine learning pipeline for real-time data processing and anomaly detection.

mental-healthdepression-screeningml-pipelinephq9healthcare-ailstm-predictionflask-apirag-llmvector dbMedical Interventions
PHQ-9 DSM-5 Based Mental Health Predictor preview

๐Ÿง  PHQ-9 AI-Powered Medical Consultation System

A full-stack mental health consultation platform integrating PHQ-9 depression screening, AI-driven predictions, and LLM-based interventions.
It enables patients to self-assess depressive symptoms and allows doctors to analyze patient progress, visualize trends, and receive AI-generated recommendations.


๐Ÿ—๏ธ System Architecture

This project is composed of two main repositories:

| Component | Tech Stack | Repository | |------------|-------------|-------------| | ๐Ÿ–ฅ๏ธ Frontend | React 18 + Vite + Tailwind CSS + Recharts + Axios | phq9-frontend | | โš™๏ธ Backend | Flask + PostgreSQL + SQLAlchemy + bcrypt + ML/AI | phq9-backend |

Architecture Overview


[ Patient / Doctor UI (React) ]
|
|  Axios (REST API)
v
[ Flask Backend (API + ML + AI) ]
|
|  SQLAlchemy ORM + Qdrant (Vector DB)
v
[ PostgreSQL + Local Models + Embeddings ]

Architecture diagram

๐Ÿš€ Key Features

๐Ÿงโ€โ™‚๏ธ Patient Portal

  • Secure registration and login
  • Daily PHQ-9 consultation submission
  • Submission history and score tracking
  • Optional notes for patient reflection

๐Ÿ‘จโ€โš•๏ธ Doctor Portal

  • Dashboard showing all patient submissions
  • Consultation history with PHQ-9 and DSM-5 details
  • Editable doctor notes
  • AI-generated predictions (future PHQ-9 scores)
  • AI-generated markdown interventions (LLM summaries)
  • Line chart visualization of score trends

๐Ÿค– AI, ML & Vector Intelligence

  • LSTM Timeline Predictor: Predicts future PHQ-9 scores and potential relapses.
  • Intervention Generator (LLM): Generates natural-language advice using context-aware retrieval.
  • Qdrant Vector DB: Stores past interventions and embeddings for semantic retrieval.
  • SentenceTransformer Embeddings: Uses BAAI/bge-m3 to create vector representations of intervention content.
  • RAG (Retrieval-Augmented Generation): Combines contextual retrieval from Qdrant with local LLM inference via Ollama (e.g., phi3, llama3).
  • Data Processing Pipeline: Includes feature normalization, correlation analysis, TF-IDF keyword extraction, and sentiment computation.

๐Ÿงฉ Tech Stack Summary

| Layer | Technology | Purpose | |-------|-------------|---------| | Frontend | React 18, Vite, Tailwind CSS 4, Recharts, Axios | UI and visualization | | Backend | Flask, SQLAlchemy, bcrypt, Flask-CORS | API & data management | | Database | PostgreSQL | Persistent data storage | | Machine Learning | TensorFlow / scikit-learn (LSTM) | Timeline & score prediction | | AI Model | Ollama (Phi-3 / LLaMA-3 local model) | Contextual intervention generation | | Vector Database | Qdrant | Semantic search & retrieval | | Embeddings | SentenceTransformer (BAAI/bge-m3) | Text vectorization for RAG |


โš™๏ธ Setup Instructions

1. Backend Setup

cd phq9-backend
python -m venv venv
venv\Scripts\activate        # (Windows)
# or source venv/bin/activate (Linux/macOS)
pip install -r requirements.txt
python app.py

Backend runs on http://localhost:5000

Additional Backend Dependencies

Make sure these services are available:

  • PostgreSQL โ†’ stores user data and PHQ-9 results
  • Qdrant โ†’ vector DB for semantic retrieval
  • Ollama โ†’ local LLM inference server

Example Ollama setup:

ollama pull phi3
ollama serve

2. Frontend Setup

cd phq9-frontend
npm install
npm run dev

Frontend runs on http://localhost:5173

Set API base URL in .env:

VITE_API_BASE_URL=http://localhost:5000/api

๐Ÿ”Œ API Overview

| Endpoint | Method | Description | | -------------------------------- | ------ | ------------------------------------ | | /api/register | POST | Register new user | | /api/login | POST | Login user | | /api/phq9/questions | GET | Fetch PHQ-9 questions | | /api/phq9/submit | POST | Submit consultation | | /api/phq9/history?user_id={id} | GET | Fetch consultation history | | /api/predictions/{userId} | GET | Fetch AI predictions & interventions | | /phq9/train-model | GET | Train ML model manually |


๐Ÿ’ป Running the Full Stack

  1. Start PostgreSQL, Qdrant, and Ollama
  2. Run Flask backend
  3. Run Vite frontend
  4. Open http://localhost:5173
  5. Register or login as a patient
  6. Submit a PHQ-9 assessment
  7. Login as Doctor (rajeev / rajeev) to view analytics, predictions, and AI interventions

๐Ÿ“Š Example Dashboard Layout

  • Top Section: AI-generated markdown intervention (full-width card)

  • Bottom Section:

    • Left (70%): Line graph of PHQ-9 trends
    • Right (30%): Scrollable consultation history cards
  • Color Legend:

    • ๐ŸŸข Green line: Actual (non-predicted) PHQ-9 scores
    • ๐Ÿ”ต Blue line: Predicted PHQ-9 scores

๐Ÿงฑ Database Schema (Simplified)

user
 โ”œโ”€ id (PK)
 โ”œโ”€ username
 โ”œโ”€ emailid
 โ”œโ”€ password (hashed)
 โ”œโ”€ role ('patient' | 'doctor')

phq9_assessment
 โ”œโ”€ id (PK)
 โ”œโ”€ user_id (FK)
 โ”œโ”€ phq9_total_score
 โ”œโ”€ patients_notes
 โ”œโ”€ doctor_notes
 โ”œโ”€ created_at

dsm_5_assessment
 โ”œโ”€ id (PK)
 โ”œโ”€ phq9_assessment_id (FK)
 โ”œโ”€ dsm5_mdd_assessment_enc
 โ”œโ”€ relapse

interventions
 โ”œโ”€ id (PK)
 โ”œโ”€ user_id (FK)
 โ”œโ”€ intervention (Markdown)
 โ”œโ”€ embedding (Vector)
 โ”œโ”€ created_at

๐Ÿง  ML & AI Flow

  1. Data Cleaning: extract_clean_data.py prepares input data, computes correlations, sentiment, and statistical features.

  2. Model Training: train_timeline_predection.py trains an LSTM on sequential PHQ-9 scores to predict future values.

  3. AI Intervention Generation: interventions.py:

    • Embeds historical interventions using SentenceTransformer (BAAI/bge-m3).
    • Stores vectors in Qdrant.
    • Retrieves relevant contexts for the current patient.
    • Sends combined context + summary prompt to Ollama (LLM).
    • Returns generated markdown to frontend.

๐Ÿงช Development Tips

  • Run backend first to avoid CORS issues
  • Monitor Ollama logs for prompt latency
  • Use ngrok for external backend access
  • Clear localStorage if auth issues occur
  • Test responsiveness using browser dev tools

๐Ÿ” Security & Privacy

  • Passwords hashed via bcrypt
  • CORS restricted to frontend origin
  • HTTPS recommended for deployment
  • Data anonymized before ML training
  • Strictly for educational and research use โ€” not clinical deployment

๐Ÿ“œ License

MIT License โ€” Copyright ยฉ 2025 Developers: Manideep & Rajeev


๐Ÿ™Œ Contributors

  • Manideep โ€” Data Science, Backend, ML/AI Pipeline
  • Rajeev โ€” Frontend, Dashboard Design, Integration

Disclaimer: This project is an educational prototype integrating PHQ-9 assessment with AI-assisted analysis. It is not intended for medical diagnosis or treatment.