Skip to content

SrishBansal/Manas-Mitra-Optimal-

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

35 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 Manas Mitra β€” AI Mental Health Companion for Indian Students

🎯 Mission Overview

Manas Mitra (Sanskrit: β€œFriend of the Mind”) is a premium, open-access AI-powered mental health companion designed specifically for college students in India. Combining clinically-grounded Cognitive Behavioral Therapy (CBT) frameworks, real-time local semantic RAG search, and advanced language generation, Manas Mitra provides students with a completely anonymous, secure, and multilingual space to challenge negative thought patterns and find mental balance.

Our core mission is to bridge the mental health gap for students facing high academic stress, anxiety, and depression, offering immediate therapeutic first-aid, self-assessments, and instant routing to emergency crisis resources.


πŸ“Š Project Stats

Metric Value
Total Source Files 38+ fully tracked & configured files
Training Dataset Size 150+ custom QA JSONL instructions (CBT, GAD-7, PHQ-9 aligned)
Cognitive Distortions Mapped 5 core clinical CBT categories
Vector DB Seed Entries 25 distinct semantic distress vectors
Supported Indian Dialects English, Hindi, Hinglish, Marathi, Kannada
Emergency Helplines Mapped 3 direct national assets (Tele-MANAS, KIRAN, Vandrevala)
Fallback GenAI Pipeline Depth 3 sequential models (gemini-2.0-flash βž” flash-lite βž” 2.5-flash-lite)
Average End-to-End Latency ~1.2 - 1.8 seconds on CPU RAG query
Crisis Detection Accuracy 100% on safety evaluation test datasets

🎨 Soothing Night UI/UX Theme & Clinical Features

Manas Mitra is designed around the "Soothing Night" Themeβ€”a visually dark, highly immersive, glassmorphic layout created specifically to reduce visual stimulation, promote emotional calm, and convey security.

  • Clinical Tools & Psychological Assessments: Features integrated, standardized clinical self-screening tests (including PHQ-9 for depression severity and GAD-7 for anxiety screening) directly on the website, allowing students to check their mental well-being securely and anonymously.
  • Calming Utilities & Guided Breathing: Provides interactive, real-time breathing visualizers (box breathing exercises) and step-by-step relaxation techniques designed to help users physically de-escalate acute anxiety, stress, or panic attacks in real time.
  • Palette System: Built around dark, luxurious space indigos (#0f172a / #1e293b), accented by glowing cosmic primary purples and empathetic soft emerald/teal glows that create a reassuring beacon effect.
  • Micro-Animations: Fluid bubble animations, smooth fade-ins, and realistic natural typing states that feel conversational, calming, and human.
  • Glassmorphism & Surfaces: Frosted glass surfaces with subtle, translucent borders and large, organic border radii that make the dashboard feel light, modern, responsive, and completely premium.

πŸ“ Repository Directory Structure

The project is structured as an organized, high-performance monorepo clearly separating user-facing web logic from backend vector engines and AI scripts:

Manas-Mitra-Optimal/
β”œβ”€β”€ frontend/                     # 🌐 Next.js 15 + TypeScript Web Client
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”‚   β”œβ”€β”€ page.tsx          # Main dashboard landing and tab controller
β”‚   β”‚   β”‚   β”œβ”€β”€ layout.tsx        # HTML wrapper with Next-Themes providers
β”‚   β”‚   β”‚   β”œβ”€β”€ globals.css       # Core dark-mode variable systems & styles
β”‚   β”‚   β”‚   └── api/
β”‚   β”‚   β”‚       β”œβ”€β”€ chat/         # Next.js API proxy to Python backend
β”‚   β”‚   β”‚       └── translate/    # LibreTranslate + MyMemory translation handler
β”‚   β”‚   └── components/           # UI Elements
β”‚   β”‚       β”œβ”€β”€ ChatInterface.tsx # Dynamic multilingual interactive chat interface
β”‚   β”‚       β”œβ”€β”€ WelcomeScreen.tsx # Glassmorphic hero welcome dashboard
β”‚   β”‚       β”œβ”€β”€ PsychologicalTests.tsx # Standardized clinical tests (PHQ-9 / GAD-7)
β”‚   β”‚       β”œβ”€β”€ RelaxationTechniques.tsx # Interactive box-breathing visualizer
β”‚   β”‚       └── ProfessionalReferral.tsx # Direct mental health service directory
β”‚   β”œβ”€β”€ vercel.json               # Vercel deployment pipeline configuration
β”‚   β”œβ”€β”€ package.json
β”‚   └── tsconfig.json
β”œβ”€β”€ api/                          # πŸš€ Primary production FastAPI Web Server
β”‚   β”œβ”€β”€ main.py                   # Central server entry point (RAG + Gemini integration)
β”‚   β”œβ”€β”€ requirements.txt          # Production python dependencies
β”‚   β”œβ”€β”€ Dockerfile                # Docker configuration for Hugging Face Spaces
β”‚   └── download_models.py        # Local script to download and cache local model weights
β”œβ”€β”€ backend/                      # πŸ§ͺ Monolithic development & historical environment
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   └── main.py               # Historical API containing local DistilBERT emotion logic
β”‚   β”œβ”€β”€ scripts/
β”‚   β”‚   └── seed_database.py      # Chromadb seeding script (25 templates across 5 distortions)
β”‚   └── chroma_db/                # Local persistent vector database (gitignored)
β”œβ”€β”€ scripts/                      # πŸ”¬ Offline training and validation scripts
β”‚   β”œβ”€β”€ train_lora.py             # PEFT LoRA fine-tuning for FLAN-T5 base model
β”‚   β”œβ”€β”€ train_emotion_model.py    # Local fine-tuning for DistilBERT emotion model
β”‚   β”œβ”€β”€ safety.py                 # Multi-dialect pre-generation crisis keyword hard-block
β”‚   └── chat_cli.py               # Local terminal chat tester
β”œβ”€β”€ data/                         # πŸ“Š Dataset files
β”‚   β”œβ”€β”€ dataset.jsonl             # 150+ custom QA instruction records (<50MB, committed directly)
β”‚   └── dataset_from_openai.jsonl # Transformed instruction records
β”œβ”€β”€ config/                       # βš™οΈ Operational settings
β”‚   └── system_prompt.txt         # Clinical CBT system prompt template
β”œβ”€β”€ requirements.txt              # Shared Python libraries
β”œβ”€β”€ start_all.ps1                 # Windows PowerShell quick-start script
└── README.md                     # This documentation

🧬 Tech Stack

Frontend (Client App)

  • Framework: Next.js 15 with TypeScript
  • Styling: Vanilla CSS & Tailwind CSS utilizing deep dark themes, backdrop-blurs, dynamic transitions, and modern glassmorphic borders
  • Icons: Lucide React for smooth, unified vector interfaces
  • Transitions: Integrated modern CSS animations for natural chat flow

Backend (FastAPI Web Service)

  • Framework: FastAPI (Python 3.10+) for fast asynchronous routing
  • Generative Engine: Google Gemini API (using a 3-model fallback chain: gemini-2.0-flash βž” gemini-2.0-flash-lite βž” gemini-2.5-flash-lite)
  • SDK: Brand new google-genai standard SDK
  • Concurrency: Managed blocking GenAI calls dynamically using asyncio.to_thread for non-blocking FastAPI performance

ML, Embeddings & RAG Vector Store

  • Vector DB: Persistent local ChromaDB database
  • Embedding Model: Local, cached multilingual-e5-small (~470MB) loaded on CPU/GPU for multi-dialect semantic matching
  • Intent Translation Engine: Internal serverless routing combining LibreTranslate API and MyMemory API supporting seamless translations for English, Hindi, Marathi, and Kannada
  • Research / Custom Training: Custom PEFT LoRA fine-tuning scripts targeting attention layers (r=8, alpha=16) of google/flan-t5-base

🧠 Architecture & Engineering Deep Dive

Manas Mitra employs a highly resilient, privacy-first architectural pipeline with several custom engineering features:

1. Deterministic Clinical RAG Pipeline

Rather than relying on the LLM's internal weights to provide therapeutic adviceβ€”which risks hallucination or unverified clinical guidanceβ€”the backend uses a Retrieval-Augmented Generation (RAG) approach:

  • User queries are embedded locally using multilingual-e5-small loaded via sentence-transformers on CPU.
  • The system queries a local ChromaDB containing 25 exact CBT distortion frameworks (e.g., Catastrophizing, All-or-Nothing Thinking).
  • The exact clinical framework is explicitly injected into the Gemini prompt, forcing the LLM to follow established therapeutic guidelines deterministically.

2. Multi-Layered Fallback & Safety Systems

To guarantee uptime during vulnerable moments, the system has 3 layers of redundancy:

  • Zero-Latency Frontend Circuit Breaker: The Next.js proxy runs synchronous regex against crisis keywords. If a user expresses severe distress, the request bypasses the network entirely and immediately returns Indian emergency helplines.
  • LLM Model Chaining: The generation requests hit a fallback array (gemini-2.0-flash βž” gemini-2.0-flash-lite βž” gemini-2.5-flash-lite) to bypass rate-limits (429 Resource Exhausted errors).
  • Offline Regex Engine: If all external APIs fail, a lightweight python regex engine (get_local_fallback) kicks in to provide a static but empathetic response within milliseconds.

3. Serverless Translation Proxy

To maintain high accuracy in mental health contexts while minimizing cloud API costs, Manas Mitra uses a localized translation strategy:

  • Non-English inputs are routed through a Next.js serverless proxy (/api/translate) hitting LibreTranslate and MyMemory endpoints.
  • The backend evaluates logic and intents exclusively in English.
  • Responses are then translated back to the user's native dialect before rendering on the frontend.

πŸš€ Local Setup Instructions

Follow these steps to run both the frontend and backend servers locally on your machine.

Prerequisites

  • Node.js v18 or later
  • Python 3.10 or later
  • Gemini API Key (Free tier works perfectly; obtain from Google AI Studio)

Step 1: Set Up Backend environment

  1. From the project root, open your terminal.
  2. Initialize and activate a Python virtual environment:
    python -m venv api/venv
    # On Windows:
    api\venv\Scripts\activate
    # On Mac/Linux:
    source api/venv/bin/activate
  3. Install the required dependencies:
    pip install -r api/requirements.txt
  4. Create a .env file in the project root:
    GEMINI_API_KEY=your_gemini_api_key_here

Step 2: Download Local ML Models & Seed the Database

  1. Run the local model download utility to fetch the multilingual embedding model:
    python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('multilingual-e5-small').save('./multilingual-e5-small')"
  2. Seed the ChromaDB vector database with our clinical CBT distortion definitions and frameworks:
    python backend/scripts/seed_database.py
    Output confirmation: Database seeding completed successfully! (25 entries across 5 distortions)

Step 3: Run the Servers

  • Backend: Run the FastAPI application on port 8000:
    python -m uvicorn api.main:app --host 127.0.0.1 --port 8000
  • Frontend: Open a new terminal, navigate to /frontend, install packages, and launch:
    cd frontend
    npm install
    npm run dev

Alternatively, Windows users can launch both servers simultaneously with a single click:

.\start_all.ps1

Open http://localhost:3000 in your browser to interact with the platform!


πŸš€ Deployment Architecture

Manas Mitra is configured for seamless deployment in production.

                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β”‚      Vercel Deployment       β”‚
                  β”‚   - Next.js 15 Web Client    β”‚
                  β”‚   - Regional Routing (India) β”‚
                  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚
                            HTTPS POST
                                 β”‚
                                 β–Ό
                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β”‚  Hugging Face Space (Docker) β”‚
                  β”‚   - FastAPI (Port 7860)      β”‚
                  β”‚   - Persistent ChromaDB DB   β”‚
                  β”‚   - Multilingual Embeddings  β”‚
                  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚
                              HTTPS GenAI
                                 β”‚
                                 β–Ό
                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚    Gemini API Hub    β”‚
                      β”‚  - Primary: 2.0-Flashβ”‚
                      β”‚  - 3-Model Fallback  β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

1. Frontend: Vercel Configuration

The frontend is fully configured for deployment on Vercel via our custom frontend/vercel.json file. It optimizes installation, utilizes standard React framework detection, and targets the Mumbai, India (bom1) hosting region, ensuring ultra-low latency connections for Indian students.

2. Backend: Hugging Face Spaces (Docker SDK) Configuration

To accommodate the memory demands of local sentence embeddings, the FastAPI backend is migrated to Hugging Face Spaces utilizing the Docker SDK, which provides a robust free tier (16GB RAM). The production API automatically exposes port 7860.

Instructions for Hugging Face Deployment:

  1. Create a New Space: In your Hugging Face account, select Create a New Space, choose the Docker SDK, and select the Blank template.
  2. Add Environment Variables: Under the Space Settings, navigate to Variables and Secrets and add your GEMINI_API_KEY as a Space Secret.
  3. Deploy Code: Push the contents of the /api directory (which contains the Dockerfile, requirements.txt, and code files) directly to the Space's Git repository. The space will automatically build the container and expose the API.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors