Skip to content

Latest commit

 

History

History
330 lines (251 loc) · 10.6 KB

File metadata and controls

330 lines (251 loc) · 10.6 KB

🧠 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!