A real-time AI-powered drowsiness detection system that monitors drivers through their camera and automatically sends SOS alerts when drowsiness is detected. Built with FastAPI, OpenCV, and deployed on Railway with PocketBase database integration.
- Real-time Face Detection: Uses OpenCV Haar cascades for robust face detection
- Eye Monitoring: Tracks eye closure patterns to detect drowsiness
- Automatic SOS Alerts: Sends alerts with location data when drowsiness is detected
- Audio Alarms: Browser-based alarm sounds using Web Audio API
- Cloud Database: Stores alerts in PocketBase with local fallback
- Responsive Web Interface: Works on desktop and mobile browsers
- Location Tracking: Automatically captures and stores location information
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Browser โ โ FastAPI โ โ PocketBase โ
โ (Camera + โโโโโบโ Server โโโโโบโ Database โ
โ Display) โ โ (AI Detection) โ โ (SOS Alerts) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ WebSocket โ โ OpenCV + โ โ Local Storage โ
โ Video Stream โ โ Computer Vision โ โ (Fallback) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
- FastAPI: Modern Python web framework with WebSocket support
- OpenCV: Computer vision library for face and eye detection
- dlib (optional): Advanced facial landmark detection
- SciPy: Scientific computing for eye aspect ratio calculations
- Geopy: Location services and geocoding
- PocketBase Python Client: Database integration
- HTML5: Modern web interface
- JavaScript: Camera access and WebSocket communication
- Web Audio API: Browser-based alarm system
- WebRTC: Real-time camera access via
getUserMedia()
- PocketBase: Cloud database for SOS alerts
- Railway: Cloud hosting platform
- Git: Version control and CI/CD
// Browser captures video from user's camera
stream = await navigator.mediaDevices.getUserMedia({ video: true });
// Sends frames via WebSocket to server for processing
ws.send(JSON.stringify({ frame: base64ImageData }));# Server processes each frame
def process_frame(frame):
# 1. Convert to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 2. Detect faces
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 3. Detect eyes within face region
eyes = eye_cascade.detectMultiScale(face_region, 1.1, 5)
# 4. Count drowsy frames
if len(eyes) < 2: # Eyes likely closed
drowsy_frames += 1
# 5. Trigger alert if threshold reached
if drowsy_frames >= DROWSY_FRAME_THRESHOLD:
raise_sos() # Send SOS alertdef raise_sos():
# 1. Get current location
location = get_current_location() # IP-based geolocation
# 2. Create alert data
sos_data = {
'details': 'Driver detected sleeping/drowsy',
'status': 'NEW',
'latitude': location['latitude'],
'longitude': location['longitude'],
'address': location['address']
}
# 3. Save to PocketBase (with local fallback)
pb.collection('sos_alerts').create(sos_data)Browser โโโโ WebSocket โโโโโบ FastAPI Server
โ โ
โโ Sends camera frames โโ Processes with OpenCV
โโ Receives processed frames โโ Detects drowsiness
โโ Updates UI status โโ Triggers SOS alerts
โโ Plays alarm sounds โโ Saves to database
- Python 3.11+
- Modern web browser with camera access
- PocketBase account (or self-hosted instance)
# Clone the repository
git clone https://github.com/BRoliix/Driver_Drowsy_Master.git
cd Driver_Drowsy_Master
# Install dependencies
cd server
pip install -r requirements.txt
# Set up environment variables
cp .env.example .env
# Edit .env with your PocketBase credentials
# Run the server
python -m uvicorn driver_drowsiness:app --host 0.0.0.0 --port 8000 --reload
# Open browser
open http://localhost:8000POCKETBASE_URL=https://your-instance.pockethost.io/
POCKETBASE_ADMIN_EMAIL=your-email@example.com
POCKETBASE_ADMIN_PASSWORD=your-passwordThis project is configured for one-click deployment on Railway:
-
Push to GitHub (already done)
-
Connect to Railway:
# Install Railway CLI npm install -g @railway/cli # Login and deploy railway login railway link railway deploy
-
Set Environment Variables in Railway dashboard:
POCKETBASE_URLPOCKETBASE_ADMIN_EMAILPOCKETBASE_ADMIN_PASSWORD
Procfile: Railway start commandrequirements.txt: Python dependencies optimized for Railwayrailway.toml: Railway configuration.env: Environment variables (not committed)
{
"id": "auto-generated",
"taxiid": "string (optional)",
"driverid": "string (optional)",
"details": "string (required)",
"status": "string (required)",
"actionedtime": "datetime",
"latitude": "number",
"longitude": "number",
"address": "string",
"created": "datetime (auto)",
"updated": "datetime (auto)"
}List/Search rule: [empty] (public access)
View rule: [empty] (public access)
Create rule: [empty] (public access)
Update rule: @request.auth.id != "" (authenticated users)
Delete rule: @request.auth.id != "" (authenticated users)
When PocketBase is unavailable, alerts are stored locally in JSON files:
local_data/sos_alerts.json- Automatic sync when connection restored
- Open the application in your browser
- Click "Start Detection" button
- Allow camera permissions when prompted
- Position your face in the camera view
- System will monitor for drowsiness automatically
- Green rectangle: Face detected successfully
- Status "Active": Driver is alert
- Status "DROWSY!": Drowsiness detected
- Frame counter: Shows drowsy frame count
- Automatic alerts: SOS sent after 8 consecutive drowsy frames
Drowsiness Detected โ Alarm Sound โ SOS Alert โ Database Save โ Location Capture
โ
Emergency contacts notified
(future enhancement)
# In driver_drowsiness.py
DROWSY_FRAME_THRESHOLD = 8 # Frames before alert (adjustable)
ALERT_COOLDOWN = 30 # Seconds between alerts
EAR_THRESHOLD = 0.25 # Eye aspect ratio threshold (if using dlib)// In HTML template
const constraints = {
video: {
width: { ideal: 640 },
height: { ideal: 480 },
frameRate: { ideal: 30 }
}
};- Face Detection: OpenCV Haar cascades identify face region
- Eye Detection: Searches for eyes within detected face
- Drowsiness Logic:
- If < 2 eyes detected โ likely closed
- Count consecutive "drowsy" frames
- Trigger alert at threshold (default: 8 frames โ 1 second)
{
"details": "Driver detected sleeping/drowsy. Immediate attention required.",
"status": "NEW",
"actionedtime": "2025-10-15T18:42:28.310055",
"latitude": 1.2959,
"longitude": 103.7907,
"address": "26A, Ayer Rajah Crescent, Singapore"
}- IP-based geolocation: Uses
geocoderlibrary - Address resolution: Reverse geocoding with Nominatim
- Fallback location: Default coordinates if services fail
- Privacy: Location only captured during alerts
function createBeepSound(frequency = 800, duration = 500) {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.frequency.value = frequency;
oscillator.type = 'sine';
// Create alert sound
oscillator.start();
oscillator.stop(audioContext.currentTime + duration / 1000);
}- Browser-compatible: No external audio files needed
- Customizable: Adjustable frequency and duration
- Non-blocking: Doesn't interfere with detection
- Auto-stop: Stops when driver becomes alert
- Frame processing: ~30 FPS capability
- CPU optimization: Efficient OpenCV operations
- Memory management: Proper cleanup of video frames
- Error handling: Graceful fallback mechanisms
- WebSocket compression: Efficient frame transmission
- Base64 encoding: Optimized image data transfer
- Connection management: Auto-reconnection on failures
- Local caching: Reduces database load
- Local processing: AI detection runs on server-side
- Minimal data: Only essential alert information stored
- No video recording: Frames processed in real-time only
- Secure transmission: WebSocket connections
- Camera access: User must explicitly grant permission
- Location: Only captured during actual alerts
- No tracking: No persistent user identification
- Data retention: Configurable alert retention policies
// Solution: Check browser permissions
navigator.permissions.query({name: 'camera'}).then(result => {
console.log(result.state); // granted, denied, or prompt
});# Check if server is running
curl -I http://localhost:8000
# Verify WebSocket endpoint
wscat -c ws://localhost:8000/ws/video# Test PocketBase connectivity
import requests
response = requests.get('https://your-instance.pockethost.io/api/health')
print(response.status_code) # Should be 200- Check lighting: Ensure adequate face illumination
- Camera positioning: Face should be clearly visible
- Browser compatibility: Use modern browsers (Chrome, Firefox, Safari)
- Performance: Close other applications to free CPU resources
Enable detailed logging:
import logging
logging.basicConfig(level=logging.DEBUG)- Detection accuracy: Frame processing success rate
- Alert frequency: Number of SOS alerts per session
- Response time: Time from detection to alert
- System performance: CPU and memory usage
# Server logs include:
print("๐จ DROWSY DETECTED!") # Alert triggered
print("โ
SOS alert saved") # Database success
print("๐ Location data: {...}") # Location capture
print("๐ Audio context initialized") # Sound system- Machine Learning: Advanced drowsiness detection with TensorFlow
- Multi-user Support: Driver profiles and personalized settings
- Emergency Contacts: Automatic SMS/email notifications
- Dashboard: Analytics and alert history
- Mobile App: Native iOS/Android applications
- Fleet Management: Multi-vehicle monitoring
- Voice Alerts: Text-to-speech warnings
- Edge Computing: On-device AI processing
- WebRTC: Peer-to-peer video streaming
- PWA: Progressive Web App capabilities
- Offline Support: Local-first architecture
- Advanced Analytics: Fatigue pattern analysis
# Fork the repository
git clone https://github.com/your-username/Driver_Drowsy_Master.git
cd Driver_Drowsy_Master
# Create feature branch
git checkout -b feature/your-feature-name
# Make changes and test
python -m pytest tests/
# Submit pull request
git push origin feature/your-feature-name- Python: Follow PEP 8 guidelines
- JavaScript: Use modern ES6+ features
- Comments: Document complex algorithms
- Testing: Add tests for new features
This project is open source and available under the MIT License.
- Issues: Report bugs on GitHub Issues
- Discussions: Ask questions in GitHub Discussions
- Documentation: Check this README and code comments
- GitHub: @BRoliix
- Project: Driver_Drowsy_Master
- OpenCV Community: Computer vision algorithms
- FastAPI: Modern Python web framework
- PocketBase: Excellent database solution
- Railway: Seamless deployment platform
- Contributors: Everyone who helped improve this project
๐ Live Demo: https://driverdrowsymaster-production.up.railway.app/
Made with โค๏ธ for safer roads and better driver awareness.