A machine learning-powered web application that analyzes typing patterns in real-time to estimate cognitive load levels. The system tracks various typing metrics (speed, pauses, backspaces, bursts) and uses a trained Gradient Boosting Regressor model to predict mental workload during typing tasks.
- Live Typing Test: Type predefined sentences while the app tracks your behavior
- Visual Feedback: Real-time character-by-character feedback (correct/incorrect/current)
- Accuracy Metrics: Track accuracy, correct/incorrect characters, and progress
- Backspace Timeline: Visual timeline showing when corrections were made
- ML-Powered Predictions: Uses trained Gradient Boosting model for accurate cognitive load estimation
- Three Load Levels: Low, Medium, High cognitive load classification
- Confidence Score: Behavior-aware confidence metric (40-95%)
- Smoothed Predictions: Rolling buffer to reduce noise and improve stability
- Anxiety Quiz: 10-question assessment with percentage scoring
- Depression Quiz: 10-question PHQ-style assessment
- Stress Quiz: 10-question perceived stress scale
- Interactive Chat Interface: Conversational UI for mental wellness check-ins
- Wellness Dashboard: View all assessment results in one place
- Label Your Sessions: Mark typing tests as low/medium/high cognitive load
- Session History: Browse and review past typing sessions
- Export Dataset: Download collected data as CSV for model retraining
- Persistent Storage: Local browser storage for history and preferences
- Flask: Python web framework for API endpoints
- scikit-learn: Machine learning library (Gradient Boosting Regressor)
- pandas: Data manipulation and feature engineering
- joblib: Model serialization and loading
- Flask-CORS: Cross-origin resource sharing support
- Vanilla JavaScript: No framework dependencies
- HTML5/CSS3: Modern, responsive UI with dark/light theme
- LocalStorage: Client-side data persistence
- Fetch API: RESTful API communication
- Model: GradientBoostingRegressor with 50 estimators
- Features: 10 engineered features (speed, intervals, pauses, corrections, bursts)
- Preprocessing: StandardScaler for feature normalization
- Validation: 5-fold cross-validation for model evaluation
- Python 3.7 or higher
- pip package manager
- Modern web browser (Chrome, Firefox, Safari, Edge)
-
Clone or extract the project
cd CTTCProject -
Install Python dependencies
pip install -r requirements.txt
Alternatively, install manually:
pip install flask flask-cors scikit-learn pandas numpy joblib
-
Verify model files exist The following pickle files should be present:
cognitive_load_model.pkl- Trained ML modelscaler.pkl- Feature scalerfeature_columns.pkl- Feature order reference
-
Start the Flask API server
python app.py
The API will start on
http://127.0.0.1:5000 -
Open the web interface Open
index.htmlin your web browser (you can double-click the file or use a local server)
- Start Test: Open
index.htmlin your browser - Type Sentence: Type the displayed sentence in the text area
- View Real-time Stats: Monitor your typing speed, pauses, backspaces, and cognitive load prediction
- Complete Test: Click "Complete Test" when finished
- Label Session: Choose a cognitive load label (low/medium/high) for dataset collection
- Access Mental Test: Click "Mental Test" button from main page
- Choose Assessment: Select Anxiety, Depression, Stress, or "Just fine"
- Answer Questions: Respond to 10 questions for each assessment type
- View Results: See your percentage scores and severity levels
- Wellness Dashboard: Click "View Wellness Dashboard" to see all results
- View History: See all past typing sessions in the history panel
- Review Sessions: Click on history items to replay typing patterns
- Export Data: Click "Export Dataset as CSV" to download collected data
- Clear Data: Use "Clear All History" to reset dataset (with confirmation)
- Click the "Toggle Theme" button to switch between dark and light modes
- Theme preference is automatically saved to localStorage
Predicts cognitive load based on typing metrics.
Request Body:
{
"speed": 4.5,
"avgInterval": 150,
"pause300": 3,
"pause500": 1,
"backspaceCount": 5,
"maxBurst": 12,
"editRatio": 0.15,
"duration": 25.4
}Response:
{
"score": 45.23,
"level": "medium",
"confidence": 78.5
}Cognitive Load Levels:
- Low: score < 35 (Minimal mental effort, comfortable typing)
- Medium: 35 β€ score < 65 (Moderate cognitive demand)
- High: score β₯ 65 (High mental effort, struggling to type)
To retrain the model with new data:
-
Update dataset.csv with your collected data
- Required columns:
speed,avgInterval,pause300,pause500,backspaceCount,maxBurst,editRatio,duration,label
- Required columns:
-
Run training script
python train_model.py
-
Review metrics
- Regression: MAE, RΒ² score
- Classification: Accuracy, F1 score, confusion matrix
- Cross-validation: 5-fold RΒ² scores
-
Updated models will be saved:
cognitive_load_model.pklscaler.pklfeature_columns.pkl
The model uses 10 engineered features:
| Feature | Description |
|---|---|
speed |
Characters per second |
avgInterval |
Average time between keystrokes (ms) |
pause300 |
Number of pauses > 300ms |
pause500 |
Number of pauses > 500ms |
backspaceCount |
Total backspace/delete presses |
maxBurst |
Longest continuous typing burst |
editRatio |
Ratio of edits to total characters |
duration |
Total typing duration (seconds) |
pause_ratio_300 |
pause300 / total_keys |
correction_rate |
backspaceCount / total_keys |
CTTCProject/
βββ app.py # Flask API server
βββ train_model.py # Model training script
βββ dataset.csv # Training dataset
βββ cognitive_load_model.pkl # Trained ML model
βββ scaler.pkl # Feature scaler
βββ feature_columns.pkl # Feature order reference
βββ index.html # Main typing tracker UI
βββ mental.html # Mental health
βββ requirements.txt # Requirement file
βββ wellness.html # Wellness dashboard UI
βββ README.md # This file
- Enter: Submit typing input
- Esc: Reset test
- ?: Show keyboard shortcuts help
- Chrome 90+ (recommended)
- Firefox 88+
- Safari 14+
- Edge 90+
- All data is stored locally in your browser's localStorage
- No data is sent to external servers except the local Flask API
- Mental health assessments are completely private
- Export/delete your data at any time
- Ensure Flask server is running on port 5000
- Check console for CORS errors
- Verify
flask-corsis installed
- Confirm all
.pklfiles exist in the project directory - Check Python version compatibility (3.7+)
- Verify scikit-learn version matches training environment
- Collect more labeled data and retrain
- Ensure consistent typing behavior during labeling
- Check feature engineering matches training
- Export dataset and clear history
- Browser storage limits vary (typically 5-10MB)
- Real-time stress monitoring with webcam (facial expressions)
- Multi-language support for typing tests
- Cloud storage integration for cross-device sync
- Advanced analytics dashboard with charts
- Mobile app version
- Calibration mode for personalized predictions
- Integration with productivity tools
Contributions are welcome! Areas for improvement:
- Additional typing test sentences and difficulty levels
- Enhanced mental health assessment questions
- Improved ML models (LSTM, Transformer architectures)
- UI/UX enhancements
- Accessibility improvements
This project is open source and available for educational and research purposes.
- Typing pattern analysis inspired by cognitive psychology research
- Mental health assessments based on GAD-7, PHQ-9, and PSS-10 scales
- Machine learning approach adapted from keystroke dynamics literature
For questions, issues, or suggestions, please create an issue in the project repository.
Note: This tool is for research and educational purposes only. Mental health assessments are not a substitute for professional psychological evaluation or treatment. If you're experiencing mental health concerns, please consult a qualified healthcare professional.