Skip to content

shubsolos19/NeuroFitAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 

Repository files navigation

🧠 NeuroFit AI β€” Know Your Body

NeuroFit Banner Status Privacy ML Chatbot

AI-powered body analysis using just your webcam β€” no server, no data upload, no account.
Get your height, BMI, body type, custom meal plan & workout routine in 5 seconds.
Then chat with your personal AI fitness coach β€” works offline too.

πŸš€ Live Demo Β· πŸ“– Docs Β· πŸ› Report Bug Β· πŸ’‘ Request Feature


πŸ“‹ Table of Contents


🌟 Overview

NeuroFit AI is a 100% browser-based body analysis tool that uses Google MediaPipe Pose to detect 33 body landmarks in real time. Within 5 seconds it estimates your height, calculates your BMI, classifies your body type using a trained Random Forest model, and generates a personalized meal and workout plan β€” all without sending a single byte to any server.

After the scan, a hybrid AI fitness chatbot pops up β€” powered by a rule-based offline engine by default, with optional Gemini AI (online) or Ollama local LLM modes.

⚠️ Disclaimer: NeuroFit is for wellness guidance only. It is not a medical device and results should not be used as medical advice.


✨ Features

Feature Description
πŸ“Έ Real-time Pose Detection 33-point landmark tracking at 30fps via MediaPipe
πŸ“ Height Estimation Camera geometry + pixel span β†’ real-world cm (Β±3–8cm)
βš–οΈ BMI Calculation Calculated from reference avg height + healthy weight for your age/gender
🧠 ML Body Classification Random Forest (50 trees, ~82% accuracy) β€” 4 classes
πŸ₯— Meal Recommendations 40-meal dataset scored by TDEE proximity + body type
πŸ’ͺ Exercise Plans Age-adjusted workout routines per body type
πŸ€– AI Fitness Chatbot Hybrid offline/online coach β€” appears after scan with your data pre-loaded
πŸ”Œ Offline Chatbot Rule-based engine β€” works with zero internet, instant responses
🌐 Online Chatbot Gemini 1.5 Flash API β€” full natural language understanding
πŸ–₯️ Local LLM Chatbot Ollama integration β€” private AI running on your own machine
πŸ”’ 100% Private All processing in-browser β€” no server, no storage
πŸ“΄ Offline Ready MediaPipe runs from local files β€” works without internet
πŸŽ‰ Staggered Reveal UI Cinematic results reveal with terminal animations + confetti

πŸ”„ How It Works

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     USER FLOW                           β”‚
β”‚                                                         β”‚
β”‚  1. Setup  β†’  Enter age, weight, gender, distance       β”‚
β”‚  2. Stand  β†’  Full body in guide box                    β”‚
β”‚  3. Detect β†’  MediaPipe maps 33 landmarks @ 30fps       β”‚
β”‚  4. Scan   β†’  5-second window averages readings         β”‚
β”‚  5. ML     β†’  Random Forest classifies body type        β”‚
β”‚  6. Score  β†’  Meals ranked by TDEE proximity            β”‚
β”‚  7. Plan   β†’  Age-adjusted exercises generated          β”‚
β”‚  8. Reveal β†’  Staggered UI reveal with animations       β”‚
β”‚  9. Chat   β†’  AI coach popup with your scan data loaded β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Height Calculation

FOV    = 60Β° (standard webcam)
frameH = 2 Γ— distance Γ— tan(FOV/2)
height = bodySpan (normalized 0–1) Γ— frameH

BMI Calculation (Updated)

BMI is now calculated using age/gender-matched reference data from CSV:

refHeight = avg height for your age + gender (from CSV)
refWeight = healthy reference weight for your age + gender
refBMI    = refWeight / (refHeight/100)Β²

Body Type Classes

Class BMI Range Focus
🦴 Underweight < 18.5 Caloric surplus, muscle gain
βœ… Normal 18.5 – 24.9 Maintenance, definition
⚠️ Overweight 25 – 29.9 Deficit, cardio
πŸ”΄ Obese β‰₯ 30 Low-impact cardio, lifestyle

πŸ›  Tech Stack

Frontend

  • Vanilla JS β€” no framework dependencies
  • HTML5 Canvas β€” real-time skeleton overlay
  • CSS3 β€” custom design system with CSS variables

ML & AI

  • Google MediaPipe Pose β€” landmark detection (local WASM)
  • Random Forest β€” body type classifier (trained in Python/sklearn, exported to JSON)
  • Harris-Benedict β€” TDEE calculation
  • JS Scoring Engine β€” meal ranking (ported from Python RF logic)
  • Rule-based NLP Engine β€” offline fitness chatbot (keyword pattern matching)
  • Gemini 1.5 Flash API β€” online chatbot mode (optional)
  • Ollama API β€” local LLM chatbot mode (optional)

Data

  • BMI Reference CSVs β€” age/gender-stratified healthy weight ranges
  • 40-meal dataset β€” 4 diet types Γ— 8 cuisines with macros
  • Exercise database β€” 40 exercises across 4 body type profiles

πŸ“ Project Structure

frontend/
β”œβ”€β”€ css/
β”‚   └── main.css              # Complete design system (CSS variables, components)
β”‚
β”œβ”€β”€ js/
β”‚   β”œβ”€β”€ scanner.js            # MediaPipe camera loop, pose detection, auto-scan
β”‚   β”œβ”€β”€ ui.js                 # Results reveal, ML calls, meal/exercise rendering
β”‚   └── chatbot.js            # Hybrid AI chatbot (offline + Gemini + Ollama)
β”‚
β”œβ”€β”€ mediapipe/                # Local MediaPipe files (offline capable)
β”‚   β”œβ”€β”€ pose.js
β”‚   β”œβ”€β”€ camera_utils.js
β”‚   β”œβ”€β”€ drawing_utils.js
β”‚   β”œβ”€β”€ pose_landmark_full.tflite
β”‚   β”œβ”€β”€ pose_solution_packed_assets.data
β”‚   β”œβ”€β”€ pose_solution_packed_assets_loader.js
β”‚   β”œβ”€β”€ pose_solution_simd_wasm_bin.js
β”‚   β”œβ”€β”€ pose_solution_simd_wasm_bin.wasm
β”‚   └── pose_web.binarypb
β”‚
β”œβ”€β”€ model/
β”‚   β”œβ”€β”€ bodyClassifier.js     # RF inference engine (browser-native)
β”‚   β”œβ”€β”€ bodyClassifier.json   # Trained RF model (50 trees, exported from sklearn)
β”‚   β”œβ”€β”€ bodyMetrics.js        # BMI labels, TDEE, CSV parsing
β”‚   β”œβ”€β”€ exercises.js          # Exercise DB + age-adjusted plan generator
β”‚   β”œβ”€β”€ meals.js              # 40-meal DB + JS scoring engine
β”‚   β”œβ”€β”€ male_bmi_final.csv    # Age-stratified male BMI reference data
β”‚   └── female_bmi_final.csv  # Age-stratified female BMI reference data
β”‚
└── index.html                # Single-page app entry point

πŸ€– ML Architecture

Body Type Classifier

Input: 7 features from MediaPipe landmarks + user BMI
       [bmi, shoulder_ratio, hip_ratio, torso_ratio,
        limb_ratio, nose_y, body_span]

Model: Random Forest
       - 50 decision trees
       - Trained on synthetic + augmented pose data
       - Exported from sklearn β†’ JSON β†’ runs in browser

Output: { label, confidence%, probabilities }
        β†’ underweight | normal | overweight | obese

Accuracy: ~82% on held-out test set
Fallback: BMI-rule classifier if model not loaded

Meal Scoring Engine

Input:  diet preference, TDEE, body type
Score:  85 base
      + calorie proximity to TDEE/5 (highest weight)
      + cuisine match for body type  (+15)
      + protein β‰₯ 25g                (+12)
      + protein β‰₯ 35g                (+8 bonus)
      + carb match (underweight)     (+12)
      + low cal (overweight/obese)   (+15)
      - high cal (overweight/obese)  (-25)
      - high fat (overweight/obese)  (-15)
      + random jitter (Β±10)          (variety)

Output: Top 6 meals ranked 1–99

πŸ’¬ AI Fitness Chatbot

After the scan completes and confetti fires, a πŸ€– AI Coach button appears at the bottom-right. The chatbot automatically opens with your scan data pre-loaded as context.

3 Modes (cycle with the toggle button)

Mode Button Label Engine Internet?
πŸ”Œ Offline Connect Online Rule-based pattern matching ❌ None needed
🌐 Online Connect LLM Gemini 1.5 Flash API βœ… Required
πŸ–₯️ Local LLM Disconnect Ollama (localhost:11434) ❌ None needed

Offline Knowledge Base

The offline engine handles 12 intent categories using keyword pattern matching:

Intent Example triggers
BMI "bmi", "body mass"
TDEE / Calories "calories", "how much should i eat"
Weight Loss "lose weight", "fat loss", "cut"
Muscle Gain "gain muscle", "bulk", "build muscle"
Workout Plan "workout", "exercise", "gym", "routine"
Diet / Nutrition "diet", "meal", "what should i eat"
Sleep & Recovery "sleep", "rest", "recovery"
Hydration "water", "hydration", "drink"
Body Type "body type", "classification"
Motivation "struggling", "give up", "hard"
Greeting "hello", "hi", "hey"
Thanks "thanks", "helpful", "awesome"

All responses are personalized using the user's actual scan numbers (TDEE, weight, BMI, body type, age).

Setting Up Online Mode (Gemini)

  1. Get a free API key from Google AI Studio
  2. Open frontend/js/chatbot.js
  3. Replace line 13:
    const GEMINI_API_KEY = 'YOUR_GEMINI_API_KEY_HERE';

Setting Up Local LLM Mode (Ollama)

  1. Install Ollama
  2. Run: ollama pull llama3.2
  3. Ollama runs automatically on localhost:11434
  4. Click the mode button twice to reach Local LLM mode
  5. To use a different model, edit line ~120 in chatbot.js:
    model: 'llama3.2', // or: mistral, phi3, gemma2

Chatbot Behaviour

  • Auto-opens 2 seconds after scan results appear
  • Resets automatically on every new scan (fresh conversation)
  • Quick chips for one-tap questions (BMI, Workout, Diet, Calories, etc.)
  • Scan data (age, BMI, TDEE, body type, diet preference) is injected as system context in online/LLM modes

πŸš€ Getting Started

πŸ“¦ Prerequisites

  • Hardware: Computer with a functional webcam
  • Software: A local web server β€” MediaPipe will not load via file:// protocol due to browser WASM security restrictions

πŸ“₯ Installation & Running

  1. Clone the Project

    git clone https://github.com/shubsolos19/neurofit-ai.git
    cd neurofit-ai
  2. Start a Local Server

    Option A: VS Code Live Server (easiest β€” right-click index.html β†’ Open with Live Server)

    Option B: Node.js

    npx serve frontend

    Option C: Python

    cd frontend
    python -m http.server 8080
  3. Open in Browser

    • Node.js: http://localhost:3000
    • Python: http://localhost:8080
  4. (Optional) Add Gemini API Key for online chatbot

    // frontend/js/chatbot.js line 13
    const GEMINI_API_KEY = 'your_key_here';

πŸ“– Usage Guide

1. Camera Setup

  • Set Distance to Camera to how far you'll stand (150–200cm recommended)
  • Set Camera Height to approximate webcam height from floor
  • Enter your Age, Weight, and Gender accurately

2. Scanning

  • Click β–Ά Start Scan
  • Step back until your full body is visible in the guide box
  • The scan starts automatically once you're detected β€” hold still for 5 seconds

3. Results

Results appear in 4 staggered blocks:

  1. Scan Measurements β€” Avg reference height, your weight, ref healthy weight, BMI (ref-based), TDEE, Age
  2. Body Type β€” ML classification with confidence score
  3. Exercises β€” 6 age-adjusted exercises for your body type
  4. Meal Plan β€” 6 scored meals (switch between Non-Veg / Vegetarian / Vegan)

4. AI Coach Chat

  • Chatbot auto-opens 2 seconds after results
  • Ask questions or tap quick-reply chips
  • Toggle between Offline / Online / Local LLM using the button in the chat header
  • Start a new scan anytime β€” chat resets automatically

Tips for Best Accuracy

  • Wear fitted clothing β€” loose clothing affects proportions
  • Ensure good lighting β€” avoid backlighting
  • Stand straight with arms slightly away from body
  • Keep feet visible in frame
  • Calibrate distance slider accurately

πŸ“Š Model Details

Random Forest JSON Schema

{
  "v": "2.1",
  "classes": ["normal", "obese", "overweight", "underweight"],
  "features": ["bmi", "shoulder_ratio", "hip_ratio", "torso_ratio",
               "limb_ratio", "nose_y", "body_span"],
  "accuracy": 0.8192,
  "trees": [
    {
      "l": false,
      "f": 4,
      "t": 0.50355,
      "L": { ... },
      "R": { ... }
    }
  ]
}

Feature Extraction

All features normalized by bodySpan for scale invariance:

Feature Landmarks Used Formula
bmi user input weight / (height/100)Β²
shoulder_ratio 11, 12 |lSho.x βˆ’ rSho.x| / bodySpan
hip_ratio 23, 24 |lHip.x βˆ’ rHip.x| / bodySpan
torso_ratio 11–24 |hipY βˆ’ shoY| / bodySpan
limb_ratio 23–28 |ankY βˆ’ hipY| / bodySpan
nose_y 0 nose.y (raw normalized)
body_span 0, 31 |groundY βˆ’ crownY|

🎯 Performance & Accuracy

Metric Value
Scan Duration 5 seconds
MediaPipe FPS ~30fps
Height Accuracy Β±3–8cm (calibration dependent)
Body Type Accuracy ~82% on test set
Model Size ~2.1MB (JSON)
Load Time (cold) ~1–2s (MediaPipe WASM)
Chatbot Response (offline) <500ms
Chatbot Response (Gemini) ~1–3s
Works Offline βœ… Yes (scanner + offline chatbot)

πŸ”’ Privacy

  • βœ… No video upload β€” camera feed never leaves your device
  • βœ… No server β€” all ML inference runs in-browser via WASM + JS
  • βœ… No account β€” no login, no tracking, no cookies
  • βœ… No storage β€” nothing written to localStorage or any database
  • βœ… Chatbot offline mode β€” rule-based engine, zero data sent anywhere
  • βœ… Open source β€” inspect every line of code yourself

⚠️ Known Limitations

  • Weight is not measured β€” entered weight is used; shown reference weight is age/gender matched healthy range
  • Height accuracy varies β€” depends on camera calibration; works best at 150–200cm distance
  • Clothing affects results β€” loose/baggy clothing can distort shoulder/hip ratios
  • Lighting matters β€” MediaPipe requires adequate lighting for accurate landmark detection
  • Single person only β€” multiple people in frame will confuse the detector
  • Mobile cameras β€” front cameras on phones have different FOV; accuracy may differ
  • Gemini chatbot β€” requires internet + valid API key; falls back to offline mode automatically on failure
  • Ollama chatbot β€” requires Ollama installed and running locally on port 11434

πŸ—Ί Roadmap

  • Multi-language support
  • Progress tracking across sessions (opt-in localStorage)
  • Export results as PDF
  • Custom calorie goal input
  • More diet categories (Keto, Paleo, Gluten-free)
  • Improved height model using camera intrinsics
  • Mobile-optimized UI
  • Chatbot voice input/output
  • Save & compare scan history

🀝 Contributing

Contributions are welcome! Here's how:

# Fork the repo, then:
git checkout -b feature/your-feature-name
git commit -m "feat: add your feature"
git push origin feature/your-feature-name
# Open a Pull Request

Areas to Contribute

  • 🍽️ Add meals to model/meals.js (follow existing schema)
  • πŸ’ͺ Add exercises to model/exercises.js
  • πŸ€– Expand chatbot knowledge base in js/chatbot.js (_KB object)
  • 🌐 Translations β€” i18n support
  • πŸ› Bug fixes β€” check open issues
  • πŸ“± Mobile UX improvements

πŸ‘¨β€πŸ’» Author

Shubham Bawari
B.Tech Computer Science β€” AKTU (2026)
πŸ“§ shubxd18@gmail.com
πŸ™ @shubsolos19


πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.


Made with ❀️ and a webcam

⭐ Star this repo if NeuroFit helped you!

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors