Skip to content

SunilDev1989/GenAIMentalWellnessTracker

Repository files navigation

🧠 MindMate – AI Mental Wellness Tracker for Exam Warriors

A Generative AI-powered mental wellness companion for students preparing for NEET, JEE, CUET, CAT, GATE, UPSC, and other competitive exams.

Python Flask Gemini AI Firebase License


🌟 What is MindMate?

MindMate addresses the silent mental health crisis among India's competitive exam aspirants. Using Google Gemini 1.5 Flash as the AI backbone and Firebase for real-time data storage, it provides:

  • 📖 AI-powered journaling – Detect hidden stress triggers, emotional patterns, and get personalized coping strategies via Gemini + Google Cloud NLP
  • 🤖 24/7 AI companion – Conversational support that understands exam context (not generic wellness chat) with smart model fallback
  • 😊 Mood intelligence – 9-point mood scale with heatmap and trend analysis stored in Firestore
  • 📊 Deep insights – Weekly AI-synthesized pattern analysis with wellness scores
  • 🌿 Mindfulness exercises – Personalized, timer-based exercises curated by AI for your current mood
  • 🆘 Crisis detection – Auto-displays iCall (9152987821) and Vandrevala helpline numbers on distress signals

🏗️ Architecture

┌─────────────────────────────────────────────────┐
│              Frontend (SPA)                      │
│   HTML5 + Vanilla CSS + Vanilla JS               │
│   Dashboard │ Journal │ Mood │ Chat │ Insights   │
└──────────────────┬──────────────────────────────┘
                   │ REST API (JSON)
┌──────────────────▼──────────────────────────────┐
│           Backend (Python Flask)                 │
│   /api/user │ /api/journal │ /api/chat           │
│   /api/mood │ /api/insights                      │
└────────┬─────────────────────┬───────────────────┘
         │                     │
┌────────▼────────┐  ┌─────────▼──────────────────┐
│ Firebase        │  │   Google Gemini AI           │
│ Firestore + Auth│  │   1.5 Flash / Flash-8B /    │
│ (real-time DB)  │  │   2.0 Flash (fallback chain) │
└─────────────────┘  └────────────────────────────┘
                      +
              Google Cloud Natural Language API
              (Sentiment analysis on journal entries)

🚀 Quick Start

Prerequisites

1. Clone & Setup

git clone https://github.com/SunilDev1989/GenAIMentalWellnessTracker.git
cd GenAIMentalWellnessTracker

2. Create Virtual Environment

python -m venv venv

# Windows
venv\Scripts\activate

# macOS/Linux
source venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

4. Configure Environment

Copy the template and fill in your keys:

cp .env.example .env

Edit .env:

GEMINI_API_KEY=your_actual_gemini_api_key_here
FLASK_SECRET_KEY=some_random_secret_string
FLASK_ENV=development

# Firebase Admin SDK (service account JSON path)
FIREBASE_CREDENTIALS_PATH=serviceAccountKey.json

# Firebase Web SDK (client-side config)
FIREBASE_API_KEY=your_firebase_api_key
FIREBASE_AUTH_DOMAIN=your_project.firebaseapp.com
FIREBASE_PROJECT_ID=your_firebase_project_id
FIREBASE_STORAGE_BUCKET=your_project.appspot.com
FIREBASE_MESSAGING_SENDER_ID=your_sender_id
FIREBASE_APP_ID=your_app_id

# Optional: Google Cloud NLP (falls back to GEMINI_API_KEY if not set)
GOOGLE_CLOUD_API_KEY=your_gcp_api_key

5. Add Firebase Service Account

Download your Firebase Admin SDK service account key from: Firebase Console → Project Settings → Service Accounts → Generate new private key

Save it as serviceAccountKey.json in the project root (it's already in .gitignore).

6. Run

python app.py

Open http://localhost:5000 in your browser! 🎉


🧪 Running Tests

pytest tests/ -v

Expected output:

tests/test_app.py::TestHealth::test_health_ok              PASSED
tests/test_app.py::TestUser::test_create_user_success      PASSED
tests/test_app.py::TestMood::test_log_mood_valid           PASSED
... (30 tests total)
======================= 30 passed in 3.84s =======================

☁️ Cloud Deployment (Google Cloud Run)

1. Build Docker Image

docker build -t mindmate .

2. Test Locally

docker run -p 8080:8080 --env-file .env mindmate

3. Deploy to Cloud Run

# Set your project
gcloud config set project YOUR_PROJECT_ID

# Build and push
gcloud builds submit --tag gcr.io/YOUR_PROJECT_ID/mindmate

# Deploy
gcloud run deploy mindmate \
  --image gcr.io/YOUR_PROJECT_ID/mindmate \
  --platform managed \
  --region asia-south1 \
  --allow-unauthenticated \
  --set-env-vars GEMINI_API_KEY=your_key,FLASK_SECRET_KEY=your_secret

🔒 Security Features

Feature Implementation
API Keys Environment variables only — never in code
Input Validation All inputs sanitized and length-limited server-side
CORS Restricted to localhost and known origins
Firebase Auth ID token verification via Firebase Admin SDK
Firebase Rules Firestore security rules enforce per-user data isolation
Crisis Detection Auto-shows helpline numbers for distress signals
Prod Server Gunicorn (not Flask debug server) in production
.gitignore serviceAccountKey.json, .env, __pycache__ excluded

📁 Project Structure

GenAIMentalWellnessTracker/
├── app.py                    # Flask application factory + auth middleware
├── gemini_helper.py          # Gemini model fallback chain (1.5-flash → 8b → 2.0-flash)
├── firebase_config.py        # Firebase Admin SDK initialization
├── requirements.txt          # Python dependencies
├── Dockerfile                # Container for Cloud Run
├── pyrefly.toml              # Type checker configuration
├── .env.example              # Environment variables template
├── .gitignore
├── README.md
│
├── routes/
│   ├── user.py               # User profile endpoints (Firestore)
│   ├── journal.py            # Journal + Gemini analysis + Cloud NLP
│   ├── chat.py               # Conversational AI (Gemini, with history)
│   ├── mood.py               # Mood logging & stats (Firestore)
│   └── insights.py           # Weekly AI insights & exercises (Gemini)
│
├── static/
│   ├── css/style.css         # Complete design system (light theme)
│   └── js/
│       ├── app.js            # Core controller, navigation, dashboard
│       ├── firebase-init.js  # Firebase JS SDK initialization
│       ├── journal.js        # Journal UI
│       ├── mood.js           # Mood tracker UI
│       ├── chat.js           # Chat UI with typing indicators
│       ├── insights.js       # Insights display
│       └── exercises.js      # Exercise cards with timer
│
├── templates/
│   └── index.html            # Single-page app entry point
│
└── tests/
    └── test_app.py           # Pytest test suite (30 tests)

🎯 How It Uses Google AI Services

1. Google Gemini AI (Primary — google-genai)

  • Journal Analysis: Deep emotional analysis → stress score, emotions, triggers, coping strategies
  • AI Companion Chat: Context-aware conversation with exam-specific system prompt and history
  • Weekly Insights: Synthesizes 14 days of mood + journal data into wellness scores and action plans
  • Mindfulness Exercises: Generates personalized exercises based on current mood and exam type
  • Model Fallback Chain: gemini-1.5-flashgemini-1.5-flash-8bgemini-2.0-flash (auto-retry on 429)

2. Google Cloud Natural Language API

  • Adds sentiment score (−1.0 to +1.0) and magnitude to every journal entry
  • Enriches the Gemini analysis with objective NLP signals
  • Endpoint: Called automatically on POST /api/journal/

3. Firebase Firestore (Real-time Database)

  • Stores users, mood logs, journal entries, chat history, exercise logs
  • Per-user subcollections: /users/{uid}/moods, /journals, /chats, /exercises

4. Firebase Authentication

  • Google Sign-In via Firebase JS SDK on the frontend
  • ID token verified server-side via Firebase Admin SDK on every write

🆘 Crisis Support

MindMate automatically detects distress signals and displays:

  • iCall (TISS): 📞 9152987821 — Mon–Sat 8am–10pm
  • Vandrevala Foundation: 📞 1860-2662-345 — 24/7 free & confidential

📊 Evaluation Criteria Alignment

Criterion Implementation
Code Quality Modular Flask blueprints, shared gemini_helper.py, docstrings, clean JS modules
Security Env vars, Firebase ID token auth, input validation, CORS, .gitignore covers secrets
Efficiency Gemini fallback chain (28s deadline), async JS, Firestore indexed queries
Testing 30 pytest tests covering all API endpoints (health, user, mood, journal, chat, insights)
Accessibility ARIA labels, role attributes, keyboard nav, focus-visible, aria-live on chat
Google Services Gemini AI + Cloud NLP + Firebase Firestore + Firebase Auth — all meaningfully integrated
Problem Alignment Exam-specific AI context (NEET/JEE/UPSC), real Gemini API, crisis detection built-in

🤝 Contributing

Pull requests welcome! For major changes, open an issue first.


📄 License

MIT License — see LICENSE for details.


Built with ❤️ for India's exam warriors. You've got this! 💪

About

Build a Generative AI-powered solution that helps students monitor and improve their mental well-being during high-stakes board exams and competitive entrance tests (e.g., NEET, JEE, CUET, CAT, GATE, UPSC).

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors