Skip to content

Baisampayan1324/Stress-Analysis-AI-System

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

2 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿง  Stress Analysis AI System

A full-stack AI-powered stress analysis application that combines Machine Learning and Large Language Models to provide personalized stress assessment and counseling recommendations.

๐Ÿ—๏ธ System Architecture

Frontend (React + TypeScript) โ†โ†’ Backend (FastAPI + Py## ๐Ÿ‘ฅ Developer Team

This project was developed by:

- **[Smit Vaghasiya](https://github.com/SmitNVaghasiya)** - Backend Developer & AI Integration
- **[Baisampayan Dey](https://github.com/Baisampayan1324)** - Frontend Developer & System Architectureโ†โ†’ ML Model + LLM (Groq)
     โ†“                              โ†“                              โ†“
  User Interface              REST API + Database           AI Analysis Engine

โœจ Features

  • ๐Ÿ“ 87-Question Stress Assessment: Comprehensive questionnaire covering various life stressors
  • ๐Ÿค– ML-Powered Analysis: Machine learning model for stress level prediction
  • ๐Ÿง  LLM Integration: Groq API integration for intelligent counseling recommendations
  • ๐Ÿ’พ Data Persistence: MongoDB Atlas database for storing sessions and results
  • ๐Ÿ“Š Export Functionality: Download results in CSV or PDF format
  • ๐ŸŽจ Modern UI: Beautiful, responsive interface with muted color scheme
  • ๐Ÿ”’ Admin Dashboard: Secure admin interface for managing responses and users
  • ๐Ÿ”„ Auto-Save Progress: Questionnaire progress saved in browser localStorage
  • โšก Optimized Performance: Connection pooling and database indexing

๐Ÿš€ Quick Start

Prerequisites

  • Frontend: Node.js 16+ and npm
  • Backend: Python 3.8+ and pip
  • API Key: Groq API key for LLM functionality
  • Database: MongoDB Atlas account (connection string in .env)

1. Frontend Setup

cd frontend
npm install
npm run dev

Frontend will run on http://localhost:8080

2. Backend Setup

cd backend
pip install -r requirements.txt

Create environment file:

cp env.example .env
# Edit .env and add your:
# - GROQ_API_KEY
# - MONGODB_URL
# - MONGODB_DATABASE
# - MONGODB_COLLECTION
# - JWT_SECRET (for admin authentication)

Start the backend:

python main.py

Backend will run on http://localhost:8020

๐Ÿ”ง Configuration

Environment Variables (.env)

# Required
GROQ_API_KEY=your_groq_api_key_here
MONGODB_URL=your_mongodb_atlas_connection_string
MONGODB_DATABASE=your_database_name
MONGODB_COLLECTION=your_collection_name
JWT_SECRET=your_jwt_secret_key_here

# Optional (defaults shown)
HOST=0.0.0.0
PORT=8020
EXPORT_DIR=exports
MAX_EXPORT_AGE_HOURS=24
JWT_EXPIRE=30d

Admin Account Security

This application no longer creates default admin accounts with hardcoded passwords for security reasons. To create an admin account, use the secure CLI script:

cd backend
python scripts/create_admin.py --email admin@yourcompany.com

You will be prompted to enter a secure password that meets complexity requirements:

  • At least 8 characters long
  • Contains uppercase and lowercase letters
  • Contains numbers
  • Contains special characters

CORS Settings

Backend is configured to accept requests from:

  • http://localhost:3000 (React dev server)
  • http://localhost:5173 (Vite dev server)
  • http://localhost:8080 (Your frontend port)

๐Ÿ“ก API Endpoints

Public Endpoints

Method Endpoint Description
GET / API status
GET /health Health check
POST /api/submit-questionnaire Submit questionnaire responses
GET /api/results/{session_id} Get analysis results

Admin Endpoints

Method Endpoint Description
POST /api/admin/login Admin authentication
POST /api/admin/create Create new admins
GET /api/admin/list List all admins
GET /api/dashboard/statistics Get dashboard statistics
GET /api/dashboard/responses Get paginated responses
GET /api/dashboard/responses/{session_id} Get detailed response
POST /api/export/{format} Export results (CSV/PDF)

Utility Endpoints

Method Endpoint Description
GET /api/questions Get questionnaire questions

๐Ÿ”„ Data Flow

  1. User submits questionnaire โ†’ Frontend sends 87 responses to backend
  2. Backend processes โ†’ ML model predicts stress level + LLM provides counseling advice
  3. Results stored โ†’ Session, responses, and analysis saved to MongoDB
  4. Frontend displays โ†’ Results shown with stress level, counseling type, urgency, and advice
  5. Admin dashboard โ†’ View all responses and detailed analysis
  6. Export available โ†’ Users can download CSV or PDF reports

๐Ÿ—„๏ธ Database Schema

Collection Structure

  • session_id: Unique identifier for each assessment
  • timestamp: When the assessment was submitted
  • user_email: Email address provided by user (optional)
  • responses: Array of 87 question responses
  • analysis: Processed results including stress score and counseling advice

Performance Optimizations

  • Indexes: Created on session_id and timestamp for faster queries
  • Connection Pooling: MongoDB connection pooling for better concurrent handling

๐Ÿค– AI Components

ML Service

  • Type: Rule-based classification (prototype)
  • Input: 66 numerical stress responses (0-7 scale) + 21 demographic responses
  • Output: Stress level (Low/Medium/High) + confidence score
  • Features: Total score, average score, high-stress response count

LLM Service (Groq)

  • Model: llama3-8b-8192 (fast, cost-effective)
  • Tasks:
    • Stress level validation/adjustment
    • Counseling type determination
    • Urgency assessment
    • Personalized advice generation
  • Fallback: Rule-based analysis if API unavailable

๐Ÿ“ฑ Frontend Components

Pages

  • Index: Main application flow (questionnaire โ†’ loading โ†’ results)
  • AdminLogin: Admin authentication page
  • AdminDashboard: Admin dashboard with response management
  • AdminManagement: Admin user management
  • NotFound: 404 error page

Components

  • StressQuestionnaire: 87-question form with demographic and stress scale options
  • StressResults: Analysis results display with export options
  • AdminNavbar: Navigation for admin pages

Features

  • Real-time API integration with backend
  • Connection status checking (shows error if backend unavailable)
  • Proper error handling with user-friendly messages
  • Loading states for better UX
  • Export functionality using backend services
  • Auto-save progress using localStorage
  • Persistent data - resumes where you left off after refresh
  • Admin dashboard with detailed response viewing

๐ŸŽจ UI/UX Features

  • Muted color scheme: Professional, calming interface
  • Responsive design: Works on all device sizes
  • Visual feedback: Clear indicators for stress levels, counseling types, and urgency
  • Accessibility: Proper contrast and readable fonts
  • Modern components: Built with Shadcn UI and Tailwind CSS

๐Ÿ” Troubleshooting

Common Issues

  1. Backend Connection Failed

    • Ensure backend server is running on port 8020
    • Check if Python dependencies are installed
    • Verify .env file configuration
  2. CORS Errors

    • Backend includes frontend port 8080 in CORS settings
    • Ensure both servers are running simultaneously
  3. Export Failures

    • Check if exports/ directory exists and is writable
    • Verify session ID is valid
    • Check backend logs for errors
  4. LLM API Errors

    • Verify GROQ_API_KEY in .env file
    • Check API quota and limits
    • System will fall back to rule-based analysis
  5. Admin Login Issues

    • Admin accounts must be created using the secure CLI script
    • Run python backend/scripts/create_admin.py --email admin@yourcompany.com
    • Check backend logs for authentication errors
    • Verify JWT_SECRET is properly configured

Debug Mode

Enable detailed logging:

cd backend
export PYTHONPATH=.
python -m uvicorn main:app --reload --log-level debug

๐Ÿš€ Development

Project Structure

stress-compass-ai/
โ”œโ”€โ”€ frontend/                 # React frontend
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ components/      # UI components
โ”‚   โ”‚   โ”œโ”€โ”€ pages/          # Page components
โ”‚   โ”‚   โ”œโ”€โ”€ utils/          # API integration and utilities
โ”‚   โ”‚   โ””โ”€โ”€ hooks/          # Custom hooks
โ”‚   โ””โ”€โ”€ package.json
โ”œโ”€โ”€ backend/                  # FastAPI backend
โ”‚   โ”œโ”€โ”€ models/             # Database models & schemas
โ”‚   โ”œโ”€โ”€ services/           # ML, LLM, export services
โ”‚   โ”œโ”€โ”€ database/           # Database connection and operations
โ”‚   โ”œโ”€โ”€ main.py             # FastAPI application
โ”‚   โ””โ”€โ”€ requirements.txt    # Python dependencies
โ””โ”€โ”€ README.md

Adding Features

  1. New API endpoints: Add to backend/src/routes/
  2. Database changes: Update backend/src/models/schemas.py
  3. Frontend components: Create in frontend/src/components/
  4. API integration: Extend frontend/src/utils/api.ts

๐Ÿ“ˆ Performance & Scalability

Current Capacity

  • Single Instance: Handles hundreds to thousands of responses
  • Optimized Database: MongoDB indexes and connection pooling
  • Frontend Caching: Questions data served from Vercel CDN
  • Data Persistence: Auto-save prevents data loss

Load Testing

  • Built-in load testing scripts in backend/load-test.js
  • Scenarios: Light, medium, and heavy load testing
  • Monitoring: Ready for MongoDB Atlas and Render metrics

๐Ÿ”ฎ Future Enhancements

  • Real ML Model: Replace rule-based with trained model
  • User Authentication: Add user accounts and history
  • Advanced Analytics: Statistical analysis and trends
  • Real-time Updates: WebSocket support
  • Multi-language: Internationalization support
  • Mobile App: React Native version

๏ฟฝ Developer Team

This project was developed by:

๏ฟฝ๐Ÿ“„ License

This project is part of the Stress Analysis System prototype.

๐Ÿค Support

For issues and questions:

  1. Check the API documentation at http://localhost:8020/docs
  2. Review backend console logs
  3. Check frontend browser console
  4. Verify environment configuration
  5. Ensure both servers are running

๐ŸŽฏ Ready to analyze stress levels with AI-powered insights!

About

An end-to-end AI-powered stress detection and personalized counseling system leveraging machine learning for psychological assessment combined with LLM-driven conversational support. Provides real-time stress metrics, personalized coping strategies, and professional-grade insights.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors