Skip to content

About

Real-time CPR technique classifier: Random Forest scores 12 biomechanical features from an interactive stick-figure UI and returns live coaching.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

CPR Quality Simulator — Technical Documentation

Overview

A full-stack ML application that classifies CPR technique quality in real time using synthetic biomechanical data and an interactive stick-figure UI.

⚠️ Disclaimer

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.


Quick Start

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:5000

Note: The .pkl files committed to this repo were trained with scikit-learn 1.8.0, which requirements.txt pins exactly. On any other version sklearn raises InconsistentVersionWarning and may return invalid results; on 1.9+ models/all_models.pkl fails to unpickle altogether. To use a newer scikit-learn, unpin it and retrain with bash run.sh.

To regenerate the dataset and retrain from scratch:

bash run.sh                    # or run_windows.bat on Windows

Or 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 :5000

Project Structure

cpr-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

Dataset — models/cpr_dataset.csv

Features (12 columns)

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

Label

  • 1 = GOOD CPR (meets all guidelines)
  • 0 = BAD CPR (one or more deficiencies)

Generation strategy

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 degraded
  • shallow — depth < 4.5 cm
  • rate_wrong — rate < 94 or > 121 /min
  • misaligned — shoulder alignment error > 10 px
  • inconsistent — high variance across all features

ML Models

1. Random Forest (chosen as best)

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:

  1. 200 decision trees trained on bootstrapped subsets of training data
  2. Each tree sees a random subset of features at each split (sqrt of total)
  3. Each tree votes on the class; majority vote wins
  4. predict_proba returns the vote fraction for each class

2. Gradient Boosting (compared)

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

3. Logistic Regression (baseline)

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

Model comparison

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

Flask API

POST /predict

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, ... }
}

GET /meta

Returns model name, accuracy, AUC, CV scores, feature importances.


UI — How the Stick Figure Works

  • 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

Coaching System

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"

Demo Script (Presentation)

  1. Open http://localhost:5000
  2. Bad posture demo: Leave elbows bent (default ~90°). Press Compress 5×. Watch verdict → POOR CPR. Coach says "Arms nearly at 90°."
  3. Fix arm angle: Drag Elbow down and out until arm straightens to 170°+. Arm turns green. Confidence rises.
  4. Fix rate: Press Compress at a steady ~100 BPM rhythm. BPM indicator turns green.
  5. Good CPR: Verdict flips to GOOD CPR with 85%+ confidence. Radar chart fills up. History blocks turn green.
  6. Show Feature Importance panel — arm angle (28%) and depth (22%) dominate.

License

MIT — see LICENSE.

About

Real-time CPR technique classifier: Random Forest scores 12 biomechanical features from an interactive stick-figure UI and returns live coaching.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages