A full-stack ML application that classifies CPR technique quality in real time using synthetic biomechanical data and an interactive stick-figure UI.
This is a software demonstration project, not a medical device, and not a substitute for accredited CPR training. The model is trained entirely on synthetic data — no real patients, rescuers, or manikin recordings were used — so its scores have not been clinically validated and must not be used to judge real resuscitation performance. Guideline thresholds referenced here (AHA/ERC 2020) are approximations used to label generated samples; consult the official guidelines and a certified instructor for actual training.
In a real emergency, call your local emergency number immediately.
Trained models and the dataset are committed to this repo, so you can run the app straight away:
git clone https://github.com/Joshayy265/cpr-simulator.git
cd cpr-simulator
pip install -r requirements.txt
python app.py # serves UI on :5000
# Open http://localhost:5000Note: The
.pklfiles committed to this repo were trained with scikit-learn 1.8.0, whichrequirements.txtpins exactly. On any other version sklearn raisesInconsistentVersionWarningand may return invalid results; on 1.9+models/all_models.pklfails to unpickle altogether. To use a newer scikit-learn, unpin it and retrain withbash run.sh.
To regenerate the dataset and retrain from scratch:
bash run.sh # or run_windows.bat on WindowsOr step by step:
pip install -r requirements.txt
python generate_dataset.py # rewrites models/cpr_dataset.csv
python train_model.py # trains 3 models, saves best
python app.py # serves UI on :5000cpr-simulator/
├── generate_dataset.py # Synthetic CPR data generator (5,000 rows)
├── train_model.py # Trains RF, GB, LR — saves best model
├── app.py # Flask backend + /predict endpoint
├── templates/index.html # Full interactive UI (canvas + Chart.js)
├── requirements.txt
├── run.sh # One-command setup (Linux/macOS)
├── run_windows.bat # One-command setup (Windows)
├── LICENSE # MIT
└── models/ # Committed — regenerated by run.sh
├── cpr_dataset.csv # 5,000 labelled biomechanical samples
├── best_model.pkl # Trained classifier (Random Forest)
├── scaler.pkl # StandardScaler (used by LR)
├── all_models.pkl # All three trained models
└── meta.json # Accuracy, AUC, feature importances
| Feature | Unit | GOOD range | Clinical source |
|---|---|---|---|
| arm_angle_deg | degrees | 160–180 | AHA 2020 guidelines |
| compression_depth_cm | cm | 5.0–6.0 | AHA/ERC 2020 |
| compression_rate_bpm | /min | 100–120 | AHA/ERC 2020 |
| shoulder_alignment_err | pixels | < 10 | Biomechanics literature |
| elbow_stability_var | degrees std | < 5 | Derived metric |
| body_inclination_deg | degrees | < 10 | Ergonomics of CPR |
| arm_symmetry_deg | degrees | < 5 | CPR manikin studies |
| depth_consistency_std | cm | < 0.5 | CPR quality metrics |
| rescuer_fatigue_index | 0–1 | < 0.2 | Fatigue literature |
| hand_position_score | 0–1 | > 0.9 | AHA hand placement |
| recoil_fraction | 0–1 | > 0.9 | ERC recoil guidelines |
| interruption_sec | seconds | < 3 | AHA no-flow time |
1= GOOD CPR (meets all guidelines)0= BAD CPR (one or more deficiencies)
5,000 samples, 50/50 class balance. BAD samples are drawn from 5 distinct deficiency profiles:
bent_arms— arm angle 70–155°, all other features degradedshallow— depth < 4.5 cmrate_wrong— rate < 94 or > 121 /minmisaligned— shoulder alignment error > 10 pxinconsistent— high variance across all features
Why RF?
- Handles non-linear relationships between features naturally
- Robust to outliers (bootstrapped trees)
- Provides feature importances directly
- No feature scaling required
- Interpretable via individual tree inspection
Architecture: 200 trees, max_depth=12, min_samples_leaf=4, class_weight='balanced'
How it works:
- 200 decision trees trained on bootstrapped subsets of training data
- Each tree sees a random subset of features at each split (sqrt of total)
- Each tree votes on the class; majority vote wins
predict_probareturns the vote fraction for each class
Why GB?
- Sequentially corrects errors of previous trees
- Often higher accuracy than RF on tabular data
- Lower variance because it corrects mistakes iteratively
Architecture: 150 estimators, max_depth=4, learning_rate=0.08, subsample=0.8
Why LR as baseline?
- Fast, fully interpretable
- Requires StandardScaler (features on different scales)
- Linear decision boundary — good for checking if the problem is linearly separable
| Property | Random Forest | Gradient Boosting | Logistic Regression |
|---|---|---|---|
| Trees | 200 independent | 150 sequential | None |
| Speed | Fast | Slower | Fastest |
| Scaling needed | No | No | Yes |
| Overfitting risk | Low (bagging) | Medium | Low |
| Feature importance | Yes | Yes | Coefficients |
| Best for | General tabular | Fine-grained patterns | Baseline/explainability |
Body: JSON with all 12 feature values
Response:
{
"label": 1,
"verdict": "GOOD CPR",
"confidence": 87.4,
"proba_good": 0.874,
"proba_bad": 0.126,
"feature_scores": { "arm_angle_deg": 0.95, ... },
"coach": { "message": "...", "cta": "..." },
"feature_importances": { "arm_angle_deg": 0.28, ... }
}Returns model name, accuracy, AUC, CV scores, feature importances.
- Three draggable joints: Shoulder, Elbow, Wrist
- Arm angle computed via dot product of vectors BA and BC at elbow
- Arm turns green (160–180°), amber (140–160°), red (<140°)
- Press Compress → animates depth, logs timestamp for BPM calc
- All 12 features sent to
/predict→ verdict + coaching returned
13 rule conditions are checked in priority order. Each returns a specific message and call-to-action. Examples:
- Arm angle < 130° → "Arms nearly at 90° — push arms straight"
- Depth < 3 cm → "Far too shallow — lean your full body weight"
- Rate > 130 → "Too fast — slow down, depth beats speed"
- All good → "Excellent technique — textbook CPR"
- Open http://localhost:5000
- Bad posture demo: Leave elbows bent (default ~90°). Press Compress 5×. Watch verdict → POOR CPR. Coach says "Arms nearly at 90°."
- Fix arm angle: Drag Elbow down and out until arm straightens to 170°+. Arm turns green. Confidence rises.
- Fix rate: Press Compress at a steady ~100 BPM rhythm. BPM indicator turns green.
- Good CPR: Verdict flips to GOOD CPR with 85%+ confidence. Radar chart fills up. History blocks turn green.
- Show Feature Importance panel — arm angle (28%) and depth (22%) dominate.
MIT — see LICENSE.