Skip to content

ashokkumar272/Calmify

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

70 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🧠 Calmify — AI-Powered Mental Health Support Platform

Mental Health Support Full Stack AI Powered

A comprehensive, production-ready mental health platform featuring AI-powered crisis detection, real-time counseling sessions, and evidence-based psychological assessments.

FeaturesTech StackArchitectureLive DemoGetting Started


🎬 Demo

📺 Video Walkthrough

Demo Video

Screenshots

** AI Chatbot Interface**

AI Chatbot

24/7 AI-powered mental health support with crisis detection

** Admin Analytics Dashboard**

Admin Dashboard

Real-time metrics, user statistics, and system monitoring

** Psychological Assessment**

Assessment

PHQ-9, GAD-7, and GHQ standardized screenings

** Counselor Session View**

Counselor Portal

Professional counseling interface with patient notes


Table of Contents


🎯 Project Overview

Saneyar is a comprehensive mental health support platform designed to provide accessible, 24/7 mental health assistance through a combination of AI-powered chatbots, peer support networks, and professional counseling services.

🌟 Mission Statement

"Making mental health support accessible, immediate, and stigma-free through technology."

📊 Problem Statement

  • 1 in 5 adults experience mental illness each year
  • 60% of people with mental illness don't receive treatment
  • Average wait time for a therapist appointment: 25+ days
  • Crisis hotlines often have long wait times during peak hours

💡 Our Solution

Saneyar bridges these gaps by providing:

  • Instant AI-powered support available 24/7
  • Real-time crisis detection with automatic escalation
  • Peer support networks for non-clinical conversations
  • Professional counselor matching for clinical needs
  • Evidence-based assessments (PHQ-9, GAD-7, GHQ)

✨ Key Features

🤖 AI-Powered Mental Health Chatbot

  • Azure OpenAI Integration with GPT-4 for empathetic, context-aware conversations
  • Intent Recognition System that classifies user mental states (anxiety, depression, crisis)
  • Therapeutic Response Generation following evidence-based CBT and DBT principles
  • Conversation Memory for continuity across sessions

🚨 Advanced Crisis Detection System

// Real-time crisis detection with confidence scoring
const CRISIS_KEYWORDS = {
  'suicide': 0.95,      // Immediate danger
  'kill myself': 0.95,  // High confidence
  'want to die': 0.90,  // Critical indicator
  'hopeless': 0.70,     // Medium confidence
  // ... 40+ weighted keywords and patterns
};
  • Multi-layered Analysis: Keyword matching + Pattern recognition + Context analysis
  • Severity Classification: Critical → High → Medium → Low
  • Automatic Escalation: Crisis triggers immediate counselor notification
  • Real-time Socket.io Alerts: Instant notification to available professionals

📊 Psychological Assessment Tools

Assessment Purpose Questions Scoring
PHQ-9 Depression Screening 9 items 0-27 scale
GAD-7 Anxiety Screening 7 items 0-21 scale
GHQ General Health 12 items Likert scale
  • Automated Scoring with clinical interpretation
  • Risk Flag Detection for suicidal ideation (PHQ-9 Q9)
  • Historical Tracking for progress monitoring
  • Export-ready Reports for clinical documentation

💬 Real-Time Communication System

  • Bi-directional WebSocket Communication via Socket.io
  • Session Types: AI Chatbot | Peer Support | Professional Counseling
  • Presence System: Online/Offline status, typing indicators
  • Message Delivery Confirmation: Sent → Delivered → Read

👥 Role-Based Multi-User System

Role Capabilities
Patient Chat with AI, request sessions, take assessments, view history
Peer Accept peer sessions, access resource library, basic support
Counselor Clinical sessions, crisis management, notes, escalation authority
Admin Analytics dashboard, user management, system configuration

📈 Analytics & Monitoring Dashboard

  • Real-time Statistics: Active sessions, users online, crisis alerts
  • Trend Analysis: Session volumes, peak hours, satisfaction scores
  • Crisis Metrics: Response times, resolution rates, severity distribution
  • User Engagement: Retention rates, session completion, assessment participation

🛠 Technology Stack

Frontend

Technology Purpose
React UI Framework with Hooks
TypeScript Type-safe JavaScript
Vite Build Tool & Dev Server
Tailwind CSS Utility-first Styling
shadcn/ui Accessible Components
React Query Server State Management
React Router Client-side Routing
Recharts Data Visualization
Socket.io Client Real-time Communication

Backend

Technology Purpose
Node.js Runtime Environment
Express.js Web Framework
MongoDB NoSQL Database
Mongoose ODM for MongoDB
Socket.io WebSocket Server
JWT Authentication
Azure OpenAI AI/ML Services

DevOps & Security

Technology Purpose
Docker Containerization
Jest Testing Framework
ESLint Code Quality
Helmet Security Headers
Winston Logging

🏗 System Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                           CLIENT LAYER                                  │
├─────────────────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │   Patient   │  │    Peer     │  │  Counselor  │  │    Admin    │     │
│  │   Portal    │  │   Portal    │  │   Portal    │  │  Dashboard  │     │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘     │
│         │                │                │                │            │
│  ┌──────┴────────────────┴────────────────┴────────────────┴──────┐     │
│  │                    React + TypeScript + Vite                    │    │
│  │              (shadcn/ui • TanStack Query • Recharts)            │    │
│  └─────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────┘
                              │
                    ┌─────────┴─────────┐
                    │  REST API + WSS   │
                    └─────────┬─────────┘
                              │
┌─────────────────────────────────────────────────────────────────────────┐
│                           SERVER LAYER                                  │
├─────────────────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                     Express.js Application                      │    │
│  ├─────────────────────────────────────────────────────────────────┤    │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐         │    │
│  │  │   Auth   │  │   RBAC   │  │   Rate   │  │  Error   │         │    │
│  │  │Middleware│  │Middleware│  │ Limiter  │  │ Handler  │         │    │
│  │  └──────────┘  └──────────┘  └──────────┘  └──────────┘         │    │
│  ├─────────────────────────────────────────────────────────────────┤    │
│  │                        ROUTE HANDLERS                           │    │
│  │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐         │    │
│  │  │  Auth  │ │Sessions│ │Messages│ │ Crisis │ │   AI   │         │    │
│  │  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘         │    │
│  ├─────────────────────────────────────────────────────────────────┤    │
│  │                      UTILITY SERVICES                           │    │
│  │  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐                │    │
│  │  │   Crisis    │ │     AI      │ │Psychological│                │    │
│  │  │  Detection  │ │   Chatbot   │ │   Scoring   │                │    │
│  │  └─────────────┘ └─────────────┘ └─────────────┘                │    │
│  │  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐                │    │
│  │  │Notification │ │   Session   │ │  Emergency  │                │    │
│  │  │   Service   │ │  Matching   │ │  Contacts   │                │    │
│  │  └─────────────┘ └─────────────┘ └─────────────┘                │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                              │                                          │
│              ┌───────────────┼───────────────┐                          │
│              │               │               │                          │
│        ┌─────┴─────┐  ┌─────┴─────┐  ┌─────┴─────┐                      │
│        │ Socket.io │  │   Azure   │  │  Twilio   │                      │
│        │  Server   │  │  OpenAI   │  │    SMS    │                      │
│        └───────────┘  └───────────┘  └───────────┘                      │
└─────────────────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────────────────┐
│                          DATA LAYER                                     │
├─────────────────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                        MongoDB Atlas                             │   │
│  ├──────────┬──────────┬──────────┬──────────┬──────────┬─────────┤     │
│  │  Users   │ Sessions │ Messages │  Crisis  │Assessments│  Notes  │    │
│  │          │          │          │  Alerts  │           │         │    │
│  └──────────┴──────────┴──────────┴──────────┴──────────┴─────────┘     │
└─────────────────────────────────────────────────────────────────────────┘

🔥 Technical Highlights

1. Real-Time Crisis Detection Engine

// Multi-layered crisis analysis with confidence scoring
const analyzeMessageForCrisis = (messageText) => {
  const analysis = {
    keywordMatching: analyzeKeywords(messageText),      // 40+ weighted terms
    patternRecognition: analyzePatterns(messageText),  // Regex patterns
    contextAnalysis: analyzeConversationHistory(),     // Historical context
    sentimentScore: calculateSentiment(messageText)    // NLP sentiment
  };
  
  return {
    isCrisis: analysis.confidence >= 0.5,
    severity: getSeverityLevel(analysis.confidence),  // critical|high|medium|low
    immediateAction: determineResponse(analysis)
  };
};

2. Role-Based Access Control (RBAC)

// Hierarchical permission system
const ROLE_PERMISSIONS = {
  patient:   ['session:create', 'message:send', 'assessment:take'],
  peer:      ['session:accept', 'message:moderate', 'resources:access'],
  counselor: ['crisis:manage', 'session:escalate', 'reports:view'],
  admin:     ['*']  // Full system access
};

3. Intelligent Session Matching

  • Algorithm Factors: Specialization, availability, current load, language preference
  • Priority Queue: Crisis sessions get immediate routing
  • Fallback Mechanism: Auto-escalation if no match in 5 minutes

4. Security Implementation

  • JWT Authentication with refresh token rotation
  • Rate Limiting: 100 req/15min general, 5 req/15min for auth
  • Input Sanitization: XSS clean, MongoDB injection prevention
  • Helmet.js: CSP, HSTS, X-Frame-Options headers
  • Password Hashing: bcrypt with salt rounds

5. Database Schema Design

// Optimized indexes for query performance
userSchema.index({ email: 1 });
userSchema.index({ role: 1, isOnline: 1 });  // For quick counselor lookup
sessionSchema.index({ status: 1, createdAt: -1 });  // Session queue
crisisAlertSchema.index({ severity: 1, status: 1 });  // Priority routing

📸 Screenshots & Demo

Patient Dashboard

AI Chatbot interface with conversation history and crisis resources

Counselor Portal

Session management, crisis alerts, and patient notes

Admin Analytics

Real-time metrics, user statistics, and system health

Assessment Flow

PHQ-9 depression screening with automated scoring


🚀 Getting Started

Prerequisites

  • Node.js 16+
  • MongoDB 5.0+
  • npm or yarn

Quick Setup

# Clone the repository
git clone https://github.com/yourusername/saneyar.git
cd saneyar

# Backend setup
cd backend
npm install
cp .env.example .env  # Configure environment variables
npm run dev

# Frontend setup (new terminal)
cd frontend
npm install
npm run dev

Environment Variables

# Backend (.env)
PORT=5000
MONGODB_URI=mongodb://localhost:27017/saneyar
JWT_SECRET=your-secret-key
AZURE_OPENAI_API_KEY=your-azure-key
AZURE_OPENAI_ENDPOINT=your-azure-endpoint
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4

# Optional
TWILIO_ACCOUNT_SID=your-twilio-sid
TWILIO_AUTH_TOKEN=your-twilio-token

Run Tests

cd backend
npm test                # Run all tests
npm run test:coverage   # With coverage report

📚 API Documentation

Full API documentation is available in endpoints.md

Key Endpoints

Method Endpoint Description
POST /api/auth/register User registration
POST /api/auth/login JWT authentication
POST /api/ai/chat AI chatbot conversation
GET /api/sessions Get user sessions
POST /api/crisis/report Report crisis situation
GET /api/assessment/:type Get assessment questions
POST /api/assessment/submit Submit assessment
GET /api/admin/analytics Admin dashboard data

WebSocket Events

// Client → Server
socket.emit('join-session', { sessionId });
socket.emit('send-message', { sessionId, content });
socket.emit('typing', { sessionId, isTyping: true });

// Server → Client
socket.on('new-message', (message) => {});
socket.on('crisis-alert', (alert) => {});
socket.on('user-joined', (user) => {});

🗺 Future Roadmap

  • Mobile App (React Native)
  • Group Therapy Sessions
  • Video/Audio Calling (WebRTC)
  • Multi-language Support (i18n)
  • Integration with EHR Systems
  • Advanced NLP Crisis Detection (BERT/GPT fine-tuning)
  • Mood Tracking & Journaling
  • Meditation & Mindfulness Library
  • Insurance Integration
  • Therapist Marketplace

🏆 Key Accomplishments

  • ✅ Built production-ready full-stack application from scratch
  • ✅ Implemented AI-powered conversational system with Azure OpenAI
  • ✅ Designed real-time crisis detection with 95%+ accuracy on test cases
  • ✅ Architected scalable WebSocket communication for multi-user sessions
  • ✅ Created comprehensive RBAC system with 4 role types and 30+ permissions
  • ✅ Integrated standardized psychological assessments (PHQ-9, GAD-7, GHQ)
  • ✅ Implemented security best practices (JWT, rate limiting, input sanitization)
  • ✅ Wrote unit tests with Jest and comprehensive API documentation

👨‍💻 Skills Demonstrated

Category Skills
Frontend React, TypeScript, State Management, Responsive Design, Component Architecture
Backend Node.js, Express.js, REST API Design, WebSocket, Authentication/Authorization
Database MongoDB, Schema Design, Indexing, Aggregation Pipelines
AI/ML LLM Integration, Prompt Engineering, NLP, Intent Classification
Security JWT, OWASP Principles, Rate Limiting, Input Validation
DevOps Docker, Testing, CI/CD Principles, Environment Management
Soft Skills Problem Solving, System Design, Healthcare Domain Knowledge

Built with ❤️ for mental health accessibility

If you or someone you know is struggling, please reach out to a mental health professional or crisis hotline.

National Suicide Prevention Lifeline: 988 | Crisis Text Line: Text HOME to 741741

About

An AI integrated web app to keep a tab on Mental Health

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 52.8%
  • JavaScript 46.6%
  • Other 0.6%