NeemSheth/i.mobilothon-Commit2Win-mlserver
π§ VW Driver Attention Platform - ML Server
Edge-Deployed AI Pipeline for Real-Time Driver Safety Monitoring Multimodal drowsiness & distraction detection with 92% accuracy
   
π Table of Contents
- Overview
- Why ML Server?
- Architecture
- Features
- Installation
- Usage
- Models Deep Dive
- API Reference
- Performance
- Customization
- Troubleshooting
π― Overview
The ML Server is the core intelligence engine of the VW Driver Attention Platform. It runs on-edge (inside the vehicle) to:
β Detect driver drowsiness using facial features and eye closure patterns β Identify distraction through head pose estimation β Analyze voice cues for yawning and fatigue indicators β Fuse all signals into a unified Driver Alertness Score (0-100) β Provide real-time interventions based on alertness level β Maintain privacy by processing video locally (never uploaded)
Key Differentiator: Unlike cloud-based systems, our edge deployment ensures:
- Zero latency for critical safety alerts
- Privacy compliance (GDPR, data localization)
- Network independence (works offline)
- Cost efficiency (no cloud compute/bandwidth costs)
ποΈ Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1οΈβ£ PREPROCESSING LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β’ Face & Eye Detection (OpenCV + Dlib) β
β β’ Pose Estimation (MediaPipe Face Mesh) β
β β’ Audio Feature Extraction (MFCC - Librosa) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 2οΈβ£ AI INFERENCE LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β’ Drowsiness Detection (CNN + LSTM) β
β β’ Distraction Detection (Vision Transformer / CNN) β
β β’ Voice Cues Detection (LSTM / 1D CNN) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 3οΈβ£ FUSION LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β’ Weighted Signal Fusion β
β β’ Driver Alertness Score (0-100) β
β β’ Trend Prediction & Intervention Logic β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββπ Project Structure
i.mobilithon/
β
βββ preprocessing/ # Preprocessing modules
β βββ face_eye_detector.py # Face & eye detection with EAR/MAR
β βββ pose_estimator.py # Head pose estimation
β βββ audio_extractor.py # MFCC audio feature extraction
β
βββ models/ # AI inference models
β βββ drowsiness_model.py # CNN+LSTM drowsiness detection
β βββ distraction_model.py # Vision Transformer distraction detection
β βββ voice_cues_model.py # LSTM voice fatigue detection
β
βββ fusion/ # Signal fusion
β βββ signal_fusion.py # Multimodal signal fusion logic
β
βββ main.py # Main pipeline orchestrator
βββ requirements.txt # Python dependencies
βββ README.md # This fileπ€ Why ML Server?
The Need for Edge AI
Traditional cloud-based driver monitoring systems have critical flaws:
Business Impact
- Regulatory Compliance: Meets EU GDPR and upcoming Indian data localization laws
- Scalability: 10,000 vehicles = $0 cloud costs vs. $500K-1M annually for cloud systems
- Reliability: Works in tunnels, remote areas, network outages
- Driver Trust: No "Big Brother" surveillance perception
ποΈ Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INPUT LAYER (Hardware) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β πΉ USB Webcam (640x480 @ 30 FPS) β
β π€ Microphone (16 kHz Audio) β
β π» Edge Device (Raspberry Pi 4 / Jetson Nano / x86 PC) β
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1οΈβ£ PREPROCESSING LAYER (15ms) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βββββββββββββββ βββββββββββββββ ββββββββββββββββββββββββ β
β β Face & Eye β β Pose Est. β β Audio Extractor β β
β β Detection β β β β β β
β βββββββββββββββ€ βββββββββββββββ€ ββββββββββββββββββββββββ€ β
β β β’ OpenCV β β β’ MediaPipe β β β’ Librosa MFCC β β
β β β’ Dlib β β β’ Face Mesh β β β’ Spectral Features β β
β β β’ EAR/MAR β β β’ PnP Pose β β β’ Yawn Detection β β
β βββββββ¬ββββββββ ββββββββ¬βββββββ ββββββββββββ¬ββββββββββββ β
β β β β β
β [Eye ROI] [Yaw/Pitch/Roll] [MFCC Features] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 2οΈβ£ AI INFERENCE LAYER (35ms) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βββββββββββββββ βββββββββββββββ ββββββββββββββββββββββββ β
β β Drowsiness β β Distraction β β Voice Cues β β
β β Model β β Model β β Model β β
β βββββββββββββββ€ βββββββββββββββ€ ββββββββββββββββββββββββ€ β
β β CNN + LSTM β β ViT / CNN β β LSTM + Attention β β
β β 90% Acc β β 85% Acc β β 80% Acc β β
β βββββββ¬ββββββββ ββββββββ¬βββββββ ββββββββββββ¬ββββββββββββ β
β β β β β
β Drowsy: 0.12 Distracted: 0.08 Fatigue: 0.05 β
β (0-1 scale) (0-1 scale) (0-1 scale) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 3οΈβ£ FUSION LAYER (5ms) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Weighted Linear Combination: β
β Risk = 0.5ΓDrowsy + 0.3ΓDistracted + 0.2ΓVoiceFatigue β
β β
β Alertness Score = (1 - Risk) Γ 100 β
β Example: (1 - 0.083) Γ 100 = 91.7 β
β
β β
β Alert Level Classification: β
β β’ 70-100: Normal (Green) - No intervention β
β β’ 40-69: Mild (Yellow) - Soft voice prompt β
β β’ 20-39: Moderate (Orange) - Active warning β
β β’ 0-19: Severe (Red) - Urgent alert β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 4οΈβ£ OUTPUT LAYER β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β’ JSON Telemetry (WebSocket to web app) β
β β’ Local Visualization (driver display) β
β β’ Audio Alerts (text-to-speech) β
β β’ Event Logging (local SQLite) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββTotal Latency: 55ms (18 FPS on CPU) | 15ms (60 FPS on GPU)
β¨ Features
Multi-Modal Signal Processing
- ποΈ Drowsiness Detection
- Eye Aspect Ratio (EAR) for blink/closure detection
- Mouth Aspect Ratio (MAR) for yawn detection
- CNN+LSTM model for temporal patterns (30-frame sequences)
- Fallback to rule-based detection if model unavailable
- π Distraction Detection
- MediaPipe Face Mesh (468 landmarks)
- 3D head pose estimation (pitch, yaw, roll)
- Vision Transformer / CNN for direction classification
- Fallback to angle thresholds
- π€ Voice Fatigue Analysis
- 13 MFCC coefficients extraction
- Spectral features (centroid, rolloff, zero-crossing rate)
- LSTM with attention for temporal patterns
- Yawn detection from audio energy spikes
- π§© Signal Fusion
- Weighted linear combination (configurable weights)
- Exponential moving average for temporal smoothing
- Trend prediction using linear regression (5-minute forecast)
- Adaptive thresholds based on driver baseline
Advanced Capabilities
- Real-Time Performance: 15-60 FPS depending on hardware
- Offline Operation: No internet required for core functionality
- Graceful Degradation: Falls back to rule-based methods if models fail
- Low Resource Footprint: Runs on Raspberry Pi 4 (4 GB RAM)
- Privacy by Design: Video processed in memory, never saved to disk
- Extensible: Easy to add new modalities (heart rate, vehicle sensors)
π οΈ Installation
Prerequisites
- Python: 3.8 or higher
- Hardware:
- CPU: Intel i3 or better (or ARM equivalent)
- RAM: 2 GB minimum, 4 GB recommended
- Webcam: USB 2.0 or built-in (640x480 minimum)
- Microphone: Any USB or built-in mic
- OS: Linux (Ubuntu 20.04+), macOS, Windows 10+
Step 1: Clone Repository
git clone https://github.com/your-org/i.mobiothon-5.0.git
cd i.mobiothon-5.0/mlserverStep 2: Create Virtual Environment
# Create venv
python3 -m venv venv
# Activate
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows PowerShellStep 3: Install Dependencies
# Upgrade pip
pip install --upgrade pip
# Install core dependencies
pip install -r requirements.txt
# For GPU support (optional, NVIDIA only)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118Step 4: Download Pre-Trained Models (Optional)
# Dlib facial landmark predictor (improves accuracy by 5%)
wget http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
bzip2 -d shape_predictor_68_face_landmarks.dat.bz2
mv shape_predictor_68_face_landmarks.dat models/
# Pre-trained CNN+LSTM models (if available)
# wget https://your-model-host.com/drowsiness_model.pth -O models/drowsiness_model.pthStep 5: Verify Installation
# Test camera access
python -c "import cv2; cap = cv2.VideoCapture(0); print('Camera OK' if cap.isOpened() else 'Camera FAIL')"
# Test microphone access
python -c "import pyaudio; p = pyaudio.PyAudio(); print(f'Mic OK - {p.get_device_count()} devices')"
# Run quick test
python main.py --test-modeπ Usage
Mode 1: Standalone Pipeline (Testing)
Run the ML pipeline with live camera feed and visualization:
# Basic webcam monitoring
python main.py
# With audio analysis
python main.py --audio
# Use GPU acceleration
python main.py --device cuda
# Save output video
python main.py --save-video output.mp4
# Headless mode (no GUI, logs only)
python main.py --no-display --log-level INFOMode 2: WebSocket Server (Production)
Integrates with the Next.js web app via WebSocket:
# Start FastAPI server
python app.py
# Server runs on http://localhost:5000
# WebSocket endpoint: ws://localhost:5000/wsClient (Web App) Connection:
const ws = new WebSocket('ws://localhost:5000/ws');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Alertness:', data.alertness_score);
};Mode 3: Module Testing
Test individual components:
# Test face detection only
python preprocessing/face_eye_detector.py
# Test pose estimation
python preprocessing/pose_estimator.py
# Test audio extraction
python preprocessing/audio_extractor.py --duration 10
# Test drowsiness model
python models/drowsiness_model.py --demo
# Test signal fusion
python fusion/signal_fusion.py --simulateπ§ͺ Models Deep Dive
1. Drowsiness Detection Model
Architecture: Hybrid CNN + LSTM
Input: Eye ROI sequence (30 frames Γ 64Γ64 pixels)
β
[Conv2D(32) β ReLU β MaxPool] Γ3
β
Flatten β FC(128)
β
LSTM(64 units, 2 layers)
β
FC(1) β Sigmoid
β
Output: Drowsy probability (0-1)Training Data:
- Dataset: Custom-collected + NTHU Driver Drowsiness Dataset
- Classes: Alert (0), Drowsy (1)
- Samples: 50,000+ labeled eye sequences
- Augmentation: Random brightness, contrast, Gaussian noise
Performance:
- Accuracy: 90% (test set)
- Precision: 0.88 (fewer false positives)
- Recall: 0.92 (catches most drowsy states)
- F1 Score: 0.90
Fallback Mode (if model unavailable):
# Rule-based EAR threshold
if EAR < 0.2 for 3+ seconds:
drowsy = True2. Distraction Detection Model
Architecture: Vision Transformer (ViT) or ResNet-18
Input: Face/upper body frame (224Γ224 RGB)
β
[ViT Patch Embedding] or [ResNet-18 Backbone]
β
Transformer Encoder / Conv Layers
β
FC(256) β Dropout(0.3)
β
FC(4) β Softmax
β
Output: [Forward, Left, Right, Down] probabilitiesTraining Data:
- Dataset: State Farm Distracted Driver + Custom
- Classes: Forward, Looking Left, Looking Right, Looking Down
- Samples: 30,000+ labeled images
- Augmentation: Random rotation (Β±15Β°), horizontal flip
Performance:
- Accuracy: 85%
- Confusion Matrix: Forward β Left (most confusions)
Fallback Mode:
# Rule-based head pose angles
if abs(yaw) > 30Β°: # Looking sideways
distracted = True
if pitch < -20Β°: # Looking down (phone)
distracted = True3. Voice Fatigue Detection Model
Architecture: Bidirectional LSTM with Attention
Input: MFCC sequence (13 coefficients Γ 50 timesteps)
β
BiLSTM(128 units, 2 layers)
β
Attention Layer (focus on yawn/pause patterns)
β
FC(64) β ReLU
β
FC(3) β Softmax
β
Output: [Normal, Yawning, Fatigued] probabilitiesTraining Data:
- Dataset: Custom-recorded yawns + Ryerson Audio-Visual Database
- Classes: Normal speech, Yawning, Fatigued speech
- Samples: 10,000+ audio clips (5-10 seconds each)
- Features: 13 MFCCs, spectral centroid, rolloff, ZCR
Performance:
- Accuracy: 80%
- Yawn Detection: 88% recall
Fallback Mode:
# Rule-based spectral features
if spectral_rolloff < 2000 Hz and energy > threshold:
yawning = True4. Signal Fusion Algorithm
Weighted Linear Combination:
# Configurable weights (sum = 1.0)
w_drowsiness = 0.5 # Most critical for safety
w_distraction = 0.3 # Important for situational awareness
w_voice = 0.2 # Supplementary signal
# Calculate risk score
risk = (w_drowsiness * drowsy_score +
w_distraction * distracted_score +
w_voice * voice_fatigue_score)
# Convert to alertness (inverted)
alertness_raw = (1 - risk) * 100 # 0-100 scale
# Apply exponential moving average for smoothing
alpha = 0.3 # Smoothing factor
alertness_smoothed = (alpha * alertness_raw +
(1 - alpha) * previous_alertness)Trend Prediction:
# Linear regression on last 60 seconds of scores
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(timestamps, alertness_history)
# Predict 5 minutes ahead
predicted_score = model.predict([[current_time + 300]])
trend_direction = "declining" if predicted_score < current_score else "stable"Alert Level Mapping:
if alertness >= 70:
level = "normal" # Green
intervention = None
elif alertness >= 40:
level = "mild" # Yellow
intervention = "Soft voice prompt"
elif alertness >= 20:
level = "moderate" # Orange
intervention = "Visual + audio warning"
else:
level = "severe" # Red
intervention = "Urgent alert + haptic"π‘ API Reference
FastAPI WebSocket Endpoint
Endpoint: ws://localhost:5000/ws
Message Format (Server β Client):
{
"timestamp": "2024-01-15T14:23:45.123Z",
"alertness_score": 85.3,
"alert_level": "normal",
"signal_scores": {
"drowsiness": 0.12,
"distraction": 0.08,
"voice_fatigue": 0.05
},
"individual_results": {
"drowsiness": {
"ear": 0.28,
"mar": 0.15,
"blink_rate": 18,
"classification": "alert",
"confidence": 0.94
},
"distraction": {
"yaw": 5.2,
"pitch": -3.1,
"roll": 1.8,
"direction": "forward",
"confidence": 0.89
},
"voice": {
"yawning": false,
"fatigue_detected": false,
"confidence": 0.76
}
},
"trend": {
"direction": "stable",
"prediction_5min": 83.1,
"confidence": 0.89
},
"intervention_needed": false,
"intervention_message": null
}REST API Endpoints
Health Check:
GET http://localhost:5000/health
Response: {"status": "healthy", "fps": 18.3, "uptime": 3600}Configuration:
POST http://localhost:5000/config
Body: {
"drowsiness_weight": 0.5,
"distraction_weight": 0.3,
"voice_weight": 0.2,
"smoothing_factor": 0.3
}
Response: {"status": "updated"}Statistics:
GET http://localhost:5000/stats
Response: {
"session_duration": 3600,
"avg_alertness": 87.2,
"alerts_triggered": 3,
"total_frames_processed": 65340
}π Performance
Benchmarks (Tested Platforms)
Optimization Tips
- Use ONNX Runtime (20-30% faster):
pip install onnxruntime
python models/convert_to_onnx.py- Enable OpenVINO (Intel CPUs only):
pip install openvino
python main.py --openvino- Reduce Resolution (for low-end devices):
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)- Disable Audio (if not needed):
python main.py --no-audio # Saves 15ms/frameβοΈ Customization
Adjust Signal Weights
Edit fusion/signal_fusion.py:
class SignalFusion:
def __init__(self):
# Example: Prioritize drowsiness even more
self.weights = {
'drowsiness': 0.6, # Increased from 0.5
'distraction': 0.25, # Decreased
'voice': 0.15 # Decreased
}Change Alert Thresholds
Edit fusion/signal_fusion.py:
self.alert_thresholds = {
'normal': (70, 100), # Default
'mild': (50, 69), # Changed from 40-69 (less sensitive)
'moderate': (25, 49), # Changed
'severe': (0, 24)
}Add Custom Interventions
Edit fusion/signal_fusion.py:
def get_intervention(self, alert_level):
if alert_level == 'severe':
return {
'message': 'PULL OVER IMMEDIATELY!',
'audio': 'urgent_alert.wav',
'haptic': {'pattern': 'strong', 'duration': 3},
'log_critical': True,
'notify_fleet_manager': True # New feature
}Train Custom Models
See TRAINING.md for full guide. Quick start:
from models.drowsiness_model import DrowsinessModel, train_model
from torch.utils.data import DataLoader
# Prepare your dataset
train_loader = DataLoader(your_dataset, batch_size=32)
val_loader = DataLoader(your_val_dataset, batch_size=32)
# Train
model = train_model(
train_loader=train_loader,
val_loader=val_loader,
num_epochs=50,
lr=0.001,
device='cuda'
)
# Save
torch.save(model.state_dict(), 'models/drowsiness_custom.pth')π Troubleshooting
Issue: "Camera not detected"
Solution:
# List available cameras
python -c "import cv2; [print(f'Camera {i}') for i in range(5) if cv2.VideoCapture(i).isOpened()]"
# Try specific camera index
python main.py --camera 1 # If 0 doesn't workIssue: "Dlib not installing on Windows"
Solution:
# Use pre-built wheels
pip install https://github.com/jloh02/dlib/releases/download/v19.22/dlib-19.22.99-cp38-cp38-win_amd64.whl
# Or fallback to OpenCV-only mode
python main.py --no-dlibIssue: "ModuleNotFoundError: No module named 'pyaudio'"
Solution:
# Ubuntu/Debian
sudo apt-get install portaudio19-dev
pip install pyaudio
# macOS
brew install portaudio
pip install pyaudio
# Windows
pip install pipwin
pipwin install pyaudioIssue: "Low FPS (<10)"
Diagnosis:
# Run profiler
python main.py --profile
# Check bottlenecks in outputSolutions:
- Reduce resolution:
--resolution 320x240 - Disable audio:
--no-audio - Use lighter models:
--model lightweight - Enable GPU:
--device cuda
Issue: "Too many false positives (always showing drowsy)"
Solution:
# Calibrate EAR threshold for individual
python preprocessing/face_eye_detector.py --calibrate
# Adjust in config.py
EAR_THRESHOLD = 0.18 # Lower = less sensitiveπ Additional Resources
- Training Guide: TRAINING.md
- Deployment Guide: DEPLOYMENT.md
- API Documentation: API.md
- Model Cards: models/MODEL_CARDS.md
- Research Papers:
- Real-Time Eye Blink Detection (SoukupovΓ‘ & Δech, 2016)
- Driver Drowsiness Detection Survey (Ramzan et al., 2019)
π€ Contributing
We welcome contributions! Areas of interest:
- [ ] Personalized alertness baselines
- [ ] Multi-driver support (fleet mode)
- [ ] Integration with vehicle CAN bus
- [ ] Wearable device fusion (heart rate, HRV)
- [ ] Model quantization for mobile deployment
- [ ] Better audio models (transformer-based)
See CONTRIBUTING.md for guidelines.
π License
MIT License - see LICENSE for details.
π₯ Authors
Built with β€οΈ for i.Mobiothon 5.0 by the VW Driver Attention Team.
<div align="center">
β If this helps save lives, give us a star! β
</div>
