SafeRoute.AI is an open-source AI-powered road safety management and hazard intelligence platform. Built for comprehensive transportation safety under the mission "Intelligent Route Planning for Safer Communities."
The platform provides real-time transparency into road hazards and safety risks using machine learning to detect dangerous patterns and promote accountability in transportation infrastructure.
-
π Real-Time Hazard Map
- Interactive Folium map with live hazard markers
- Hazard clustering and hotspot detection
- Heat map overlay for hazard density
- Multiple tile providers and filtering options
-
π¨ AI Anomaly Detection
- Machine learning for suspicious hazard patterns
- Isolation Forest algorithm for outlier detection
- Interactive visualization with hover details
-
π’ Vendor/Location Analysis
- Hotspot identification and risk zones
- Hazard distribution analysis
- Temporal trend patterns
-
β±οΈ Safety & Efficiency Tracking
- Route optimization analysis
- Processing time monitoring
- Hazard response tracking
- Modern UI: Clean, responsive design with Streamlit
- Brand Consistency: Professional color scheme and typography
- Accessibility: WCAG AA compliant with proper contrast ratios
- Real-time Data: Integration with multiple APIs and data sources
- Project Structure
- Installation & Setup
- Configuration Files
- Features
- API Integration
- Database Schema
- Security
- Performance Monitoring
- Usage Guide
- Troubleshooting
SafeRoute-AI/
βββ config/ # Configuration files
β βββ __init__.py # Package initialization
β βββ app_config.py # Application settings
β βββ api_config.py # API configurations
β βββ database_config.py # Database schema
β βββ security_config.py # Security policies
β βββ performance_config.py # Performance monitoring
β βββ logging_config.py # Logging setup
β
βββ utils/ # Utility modules
β βββ __init__.py
β βββ config.py # Core configuration
β βββ database.py # Database manager
β βββ error_handling.py # Error handling & validation
β βββ performance.py # Performance utilities
β βββ cache_manager.py # Caching system
β
βββ components/ # UI/Feature components
β βββ __init__.py
β βββ hazard_map.py # Interactive map
β βββ enhanced_route_planner.py # Route planning
β βββ enhanced_safety_gpt.py # AI recommendations
β βββ enhanced_data_ingestion.py # Data collection
β βββ community_reporting.py # User reporting
β βββ real_mapbox_integration.py # Mapbox API
β
βββ models/ # ML/Data models
β βββ __init__.py
β βββ hazard_clustering.py # DBSCAN clustering
β βββ image_verification.py # Image analysis
β
βββ data/ # Data storage
β βββ sample_data.py # Sample data
β βββ guidelines/ # Safety guidelines
β βββ uploads/ # User uploads
β βββ exports/ # Exported data
β βββ safetroute.db # SQLite database
β
βββ logs/ # Application logs
β βββ safetroute.log # Main log
β βββ errors.log # Error log
β
βββ backups/ # Database backups
β
βββ app_final.py # Main application
βββ setup_environment.py # Environment setup
βββ deploy_production.py # Production deployment
βββ run_app.bat # Windows runner script
βββ requirements.txt # Python dependencies
βββ .env # Environment variables
βββ LICENSE # License file
βββ README.md # This documentation
- Python 3.8 or higher
- pip (Python package manager)
- Clone or download the project
# If using git
git clone <repository-url>
cd SafeRoute-AI
# Or simply extract the project folder- Install dependencies
pip install -r requirements.txt- Configure Environment
Create
.envfile with your API keys:
OPENAI_API_KEY=your_openai_key_here
MAPBOX_ACCESS_TOKEN=pk.your_mapbox_token_here
WEATHER_API_KEY=your_weather_api_key_here- Initialize Database
python -c "from config.database_config import DatabaseConfig; DatabaseConfig.initialize_database()"- Run the application
streamlit run app_final.pyOpen your browser and navigate to http://localhost:8501
Run the setup script
.\run_app.batThis script will automatically:
- Check for Python installation
- Create a virtual environment
- Install all dependencies
- Launch the dashboard
- Mapbox API - Real-time traffic and hazard data
- OpenAI GPT - Safety recommendations and analysis
- OpenWeatherMap - Weather conditions
- User community reports - Crowdsourced hazard data
- Generated realistic road hazard scenarios
- Includes hazards from multiple categories (potholes, flooding, accidents)
- Temporal data for trend analysis
SafeRoute-AI/
βββ config/ # Configuration Package
β βββ __init__.py # Package initialization
β βββ app_config.py # Application settings & feature flags
β βββ api_config.py # API endpoints & configurations
β βββ database_config.py # Database schema definitions
β βββ security_config.py # Security policies & validation
β βββ performance_config.py # Performance monitoring settings
β βββ logging_config.py # Logging configuration
β
βββ utils/ # Utility Modules
β βββ __init__.py
β βββ config.py # Core configuration loader
β βββ database.py # Enhanced DatabaseManager
β βββ error_handling.py # Error handling & validation decorators
β βββ performance.py # Performance monitoring utilities
β βββ cache_manager.py # Redis + memory caching system
β
βββ components/ # Feature Components
β βββ __init__.py
β βββ hazard_map.py # Interactive Folium map
β βββ enhanced_route_planner.py # Smart route planning
β βββ enhanced_safety_gpt.py # AI-powered recommendations
β βββ enhanced_data_ingestion.py # Real-time data aggregation
β βββ community_reporting.py # User hazard reporting
β βββ real_mapbox_integration.py # Mapbox API integration
β
βββ models/ # ML/Data Models
β βββ __init__.py
β βββ hazard_clustering.py # DBSCAN clustering for hotspots
β βββ image_verification.py # YOLOv8 object detection
β
βββ data/ # Data Storage
β βββ sample_data.py # Sample data utilities
β βββ guidelines/ # Safety guidelines
β βββ uploads/ # User uploads
β βββ exports/ # Exported data
β βββ safetroute.db # SQLite database
β
βββ logs/ # Application Logs
β βββ safetroute.log # Main application log
β βββ errors.log # Error log
β
βββ backups/ # Database Backups
βββ app_final.py # Main Streamlit application
βββ requirements.txt # Python dependencies
βββ .env # Environment variables
βββ .gitignore # Git ignore rules
βββ LICENSE # License file
βββ README.md # Documentation
The dashboard supports multiple data sources accessible via the sidebar:
- Real-time APIs: Live data from Mapbox, weather services
- Community Reports: Crowdsourced hazard data
- Sample Data: Generated dataset for demonstration
Edit config/ files to modify:
- API endpoints and credentials
- Anomaly detection parameters
- Styling and colors
- Analysis thresholds
- Security policies
Key Configuration Files:
config/app_config.py - Feature flags and app settings
config/api_config.py - API endpoints and keys
config/database_config.py - Database schema and settings
config/security_config.py - Authentication and permissions
config/performance_config.py - Monitoring and alerts
config/logging_config.py - Logging levels and outputs
Purpose: Application-wide settings and feature flags
Key Settings:
APP_NAME = "SafeRoute.AI"
APP_VERSION = "1.0.0"
DEBUG = True # Set to False in production
FEATURES = {
'community_reporting': True,
'ai_recommendations': True,
'image_verification': True,
'real_time_updates': True,
'hazard_clustering': True,
'route_planning': True,
'admin_dashboard': True
}Purpose: API endpoints and service configurations
Supported APIs:
- Mapbox: Geocoding, Directions, Traffic, Static Maps
- OpenAI: GPT models for recommendations
- Weather: OpenWeatherMap for weather data
Purpose: Database schema, indexes, and management
Tables Created:
- hazards: Road hazard reports
- users: User accounts and profiles
- routes: Calculated routes
- recommendations: AI recommendations
Purpose: Security policies, password handling, and validation
Security Features:
- SHA-256 password hashing with salt
- Session timeout management
- Rate limiting configuration
- File upload validation
Purpose: Performance monitoring and optimization
Monitoring Features:
- API response time tracking
- Database query monitoring
- Memory and CPU usage alerts
Purpose: Comprehensive application logging
Log Levels:
- DEBUG, INFO, WARNING, ERROR, CRITICAL
- Algorithm: DBSCAN clustering from scikit-learn
- Features: Location, hazard type, severity
- Output: Hotspot identification and risk zones
- Visualization: Interactive map overlays
- Smart route calculation considering hazards
- Multiple route alternatives (safe, fast, balanced)
- Safety score computation (0-100 scale)
- Real-time hazard avoidance
- Identifies suspicious hazard patterns
- Statistical outlier detection
- Temporal anomaly analysis
- Visual highlighting of suspicious zones
- Primary: #1f77b4 (Professional Blue)
- Success: #2ca02c (Safety Green)
- Warning: #ff7f0e (Alert Orange)
- Danger: #d62728 (Hazard Red)
- Background: #f8f9fa (Light gray)
- Text: #333333 (Dark gray)
- Clean, minimal design
- Ample white space
- Consistent spacing (8px grid)
- Mobile-responsive layouts
- Interactive elements
- Geocoding: Address to coordinates conversion
- Directions: Route calculation and optimization
- Traffic: Real-time traffic incident data
- Static Maps: Map image generation
- GPT-3.5-turbo: Fast, cost-effective recommendations
- Safety Analysis: IRC and MoRTH compliance checking
- Current Conditions: Real-time weather data
- Forecasts: Weather predictions for route planning
CREATE TABLE hazards (
id TEXT PRIMARY KEY,
hazard_type TEXT NOT NULL,
severity INTEGER (1-5),
confidence REAL (0-100),
lat REAL, lon REAL,
location TEXT,
description TEXT,
source TEXT,
verified BOOLEAN,
timestamp DATETIME
)CREATE TABLE users (
username TEXT PRIMARY KEY,
password_hash TEXT,
email TEXT,
role TEXT (user/admin/moderator)
)CREATE TABLE routes (
id TEXT PRIMARY KEY,
start_lat REAL, start_lon REAL,
end_lat REAL, end_lon REAL,
route_data TEXT (JSON),
safety_score INTEGER (0-100)
)CREATE TABLE recommendations (
id TEXT PRIMARY KEY,
area TEXT,
recommendation_data TEXT (JSON),
priority TEXT (Low/Medium/High/Critical)
)- SafeRoute.AI is now a public-access application with no login required
- All features are available to all users without authentication
- Anyone can report hazards and view real-time safety data
- All user inputs are validated for safety and correctness
- File uploads are restricted to safe image formats (JPG, JPEG, PNG)
- Maximum Size: 10 MB
- Community reports are stored anonymously
- User location data is not personally identifiable
- All data is stored locally in the application database
- Validation: MIME type + extension verification
- Password hashing with salt
- SQL injection prevention
- XSS protection
- HTTPS recommended for production
- API Response Time (target < 1000ms)
- Database Query Time (target < 500ms)
- Page Load Time (target < 3000ms)
- Memory Usage (alert > 80%)
- CPU Usage (alert > 85%)
- Cache Hit Rate (target > 70%)
-
View Hazard Map
- Open application
- Click "Live Hazard Map" tab
- Use filters to find specific hazards
- Click markers for detailed information
-
Report a Hazard
- Click "Report Hazard" tab
- Select hazard type and severity
- Add description and optional photo
- Submit report for verification
-
Plan Safe Route
- Click "Safe Route Planner" tab
- Enter start and end locations
- Choose route preference (Safe/Fast/Balanced)
- View recommended route with safety score
-
View Analytics
- Click "Analytics & Admin" tab
- Monitor trend analysis
- Check system performance metrics
- Review implementation status
-
Manage Reports
- Review pending community reports
- Verify submissions with image analysis
- Update recommendation status
- Monitor verification rates
-
System Maintenance
- Backup database regularly
- Monitor log files
- Clean up old data
- Update configurations and API keys
streamlit run app_final.pyCreate .env with production values:
DEBUG=False
export DEBUG=False
streamlit run app_final.py --logger.level=warningDeployment Platforms:
- Streamlit Cloud
- Heroku
- AWS/Azure/GCP
- Docker containers
- On-premise servers
Solution:
pip install -r requirements.txtSolution:
# Close other database connections
# Or use automatic connection pooling in database.pySolution:
- Verify
.envfile exists in project root - Check all required keys are set
- Restart application after changes
- Verify key format is correct
Solution:
- Check internet connection
- Verify API keys are valid and active
- Check firewall and proxy settings
- Verify API rate limits not exceeded
Solution:
- Reduce cache size in
config/app_config.py - Enable data cleanup in database settings
- Reduce log retention period
- Restart application to free memory
Solution:
- Check database indexes are created
- Monitor query performance using logs
- Enable caching for frequently accessed data
- Increase timeout values if needed
- Check CPU and memory availability
OPENAI_API_KEY- OpenAI API keyMAPBOX_ACCESS_TOKEN- Mapbox token
WEATHER_API_KEY- OpenWeatherMap keyGOOGLE_MAPS_API_KEY- Google Maps keyDEBUG- Debug mode (True/False)CACHE_TIMEOUT- Cache timeout in secondsHAZARD_UPDATE_INTERVAL- Update interval in seconds
This project welcomes contributions. To contribute:
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests
- Submit a pull request
Open Source - See LICENSE file for details
- Open source community for tools and libraries
- Contributors who help improve road safety
- Communities benefiting from safer transportation
For technical issues or questions:
- Check troubleshooting section above
- Verify Python environment meets requirements
- Ensure internet connectivity for API features
- Review logs in
logs/directory - Check project documentation
Built with β€οΈ for Safer Roads and Smarter Communities
SafeRoute.AI - Intelligent Route Planning for Safer Communities