AI-Powered Travel Safety Engine with Real-Time Environmental Intelligence
Features β’ Tech Stack β’ Architecture β’ Getting Started β’ API Reference β’ Demo
SafeNav is a full-stack, health-aware travel safety platform that synthesizes live environmental data (weather, air quality, traffic incidents) with Google Gemini AI to deliver personalized safety directives, optimized routing, and AI-generated itineraries β all tailored to individual user health profiles.
Deterministic Output Layer: SafeNav transforms unstructured environmental data into deterministic, machine-readable safety signals using a hybrid of rule-based mathematical heuristics and LLM-assisted generation. This ensures stable and predictable safety scoring despite noisy, real-world inputs.
| Resource | Link |
|---|---|
| Video Walkthrough | Google Drive |
| GitHub Repository | github.com/mohamad-shafeez/SafeNav |
- Composite Safety Score (0β150) computed from cumulative environmental stress and user-specific health vulnerabilities
- Exposure Multiplier β risk scales non-linearly with travel duration (30 min = 1.0Γ, 60 min = 1.5Γ, 120+ min = 2.0Γ)
- Adaptive Thresholds β heat limits dynamically adjust based on medical profile (31Β°C for cardiac/elderly vs. 38Β°C for standard)
- Physical Exertion Penalty β walking in extreme conditions triggers a heart-strain penalty proportional to duration
- AQI Sensitivity β respiratory health alerts fire at 55 AQI for asthma profiles vs. 100 AQI for standard users
- TomTom-powered routing with real-time traffic delay analysis from
trafficDelayInSeconds - Live Incident Intelligence β BBox scanning fetches accidents, fog, lane closures (capped at 50 items) via TomTom's
incidentDetailsAPI - Dual-Engine Scoring β SafeNav route (green, health-optimized) vs. Fastest route (orange/red, speed-optimized)
- Comprehensive Analytics β fuel consumption, COβ emissions, toll costs, safety score, road type breakdown
- Haversine Distance β server-side geodesic calculations for precise coordinate math
- Safety Directives β
gemini-1.5-flashgenerates 1-sentence personalized safety advice in raw text - Itinerary Generator β
gemini-1.5-flashproduces structured JSON travel plans respecting budget, vibe, health constraints - Smart Chat β conversational AI travel assistant
- Image Analysis (OCR) β extract and translate text from images using Gemini Vision
- Document Translation β translate PDF/TXT documents across 19 languages
- Retry Shield β exponential backoff (wait = attempt Γ 20s) with API key rotation for 429/503 resilience
- Real-time Weather Risk Scoring β thunderstorm and flood risk penalties from OpenWeatherMap
- Regional Heuristics β latitude-based risk adjustments for seasonal hazard zones
- Tiered Classification β Low / Medium / High risk with TTS-ready alert messages
- Multi-Tier Encryption β Standard (AES-256), Military-Grade (AES + HMAC), Biometric, and Quantum-Resistant tiers
- AI Document Analysis β Gemini Vision extracts and validates data from Passports, Visas, IDs, Medical Reports
- File Integrity β SHA-256 checksums and entropy validation before storage
- 22 Document Types β Passport, Aadhar, PAN, Visa, Travel Insurance, Medical Reports, Forex Receipts, and more
- Secure Lifecycle β upload β AI analysis β encryption β storage β decryption β secure wipe
- Real-Time Voice Alerts β TTS-powered spoken warnings for extreme heat, poor air quality along the active route
- Hydration Reminders β periodic alerts for walking users based on live heat-strain parameters
- Multi-Language TTS β supports 19 languages including Hindi, Tamil, Telugu, Japanese, Korean, and more
- Speech-to-Text Analysis β audio file transcription via Google Cloud Speech API
- Smart Chat β context-aware conversational travel assistant
- Universal Translator β text, image (OCR), and document translation across 19 languages
- Itinerary Planner β budget-aware, health-conscious AI trip planning with structured JSON output
- Image Proxy β secure Unsplash integration for destination imagery
- JWT-Verified Admin Dashboard β Firebase token authentication with hardcoded admin whitelist
- User Management β ban, unban, delete users, and modify roles via Firebase Auth + Firestore
- Kill Switch β system-wide threat level control (L0βL3) with immutable audit logging
- API Quota Monitoring β real-time tracking of OpenWeatherMap, WAQI, Gemini, and Nominatim usage
- Vault Purge β admin-level document force-deletion with audit trail
- Health Profile Analytics β aggregated user health condition statistics
- Stale-While-Revalidate caching strategy β app shell loads instantly while assets refresh in background
- Offline Fallback β graceful 404 page when navigation fails offline
- Smart Cache Exclusions β API calls, Firebase, external map tiles, and weather radar are never cached
- Installable β standalone display with maskable icons (192px, 512px)
| Layer | Technologies |
|---|---|
| Frontend | HTML5, CSS3 (Custom Glassmorphism UI), Vanilla JavaScript (ES6+), MapLibre GL JS, Leaflet.js, Capacitor |
| Backend | Python 3.12, Flask 3.1.2, Flask-CORS, Gunicorn 25.1.0 |
| AI / ML | Google Gemini 1.5 Flash (google-generativeai 0.8.6, google-genai 1.64.0) |
| Navigation | TomTom Routing API, TomTom Incidents API, Polyline Encoding |
| Environmental | OpenWeatherMap (Weather), WAQI (Air Quality Index), RainViewer (Radar) |
| Image | Unsplash API (Destination Imagery), Pillow (Image Processing) |
| Document | PyPDF2 (PDF Parsing), Gemini Vision (OCR & Validation) |
| Security | Firebase Admin SDK, JWT Verification, Fernet Encryption (AES-256-CBC), PBKDF2-HMAC-SHA256, SHA-256 Checksums |
| PWA | Service Workers (Stale-While-Revalidate), Web App Manifest, Capacitor (Native Bridge) |
| Hosting | Render (Backend API), Firebase Hosting (Frontend), Vercel (Serverless Fallback) |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT (Frontend) β
β HTML5 + CSS3 (Glassmorphism) + Vanilla JS + MapLibre + Leaflet β
β Firebase Auth (JWT) β Service Worker (PWA) β Capacitor (Mobile) β
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β HTTPS / REST API
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GATEWAY (Flask API) β
β CORS Enforcement β Blueprint Router β JWT Validation β
β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β β Route β βPredictionβ β Planner β β Vault β β Admin β β
β β Blueprintβ β Blueprintβ β Blueprintβ β Blueprintβ β Blueprintβ β
β ββββββ¬ββββββ ββββββ¬ββββββ ββββββ¬ββββββ ββββββ¬ββββββ ββββββ¬ββββββ β
βββββββββΌβββββββββββββΌβββββββββββββΌβββββββββββββΌβββββββββββββΌβββββββββ
βΌ βΌ βΌ βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LOGIC ENGINE (Services) β
β β
β βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββββ β
β β Route Engine β βPrediction Engine β β Documents Engine β β
β β (TomTom API) β β(Weather+AQI+AI) β β (Encrypt+AI+OCR) β β
β ββββββββββ¬βββββββββ ββββββββββ¬ββββββββββ ββββββββββ¬βββββββββββ β
β ββββββββββ΄βββββββββ ββββββββββ΄ββββββββββ ββββββββββ΄βββββββββββ β
β β Stay Engine β β Planner Engine β β Security Manager β β
β β(Weather+Heuristic) β(Gemini Itinerary)β β(Fernet+AES+HMAC) β β
β βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββββ
β External APIs β β Firebase / GCP β β Local Storage β
β TomTom β β Firestore β β vault_storage/ β
β OpenWeatherMapβ β Auth β β encrypted_files/ β
β WAQI β β Analytics β β keys/ β
β Unsplash β β Audit Logs β β metadata.json β
β Nominatim β β β β β
βββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββββ
safenav/
βββ backend/
β βββ app.py # Flask application factory & entry point
β βββ config.py # Vault storage paths & file validation
β βββ vercel.json # Vercel serverless deployment config
β βββ requirements.txt # Python dependencies (pinned versions)
β β
β βββ routes/ # Flask Blueprints (API layer)
β β βββ auth.py # Authentication endpoint stub
β β βββ route.py # Routing, analytics, cost, weather, optimization
β β βββ prediction.py # Environmental risk prediction endpoint
β β βββ planner.py # AI trip planner endpoint
β β βββ stays.py # Stay safety analysis endpoint
β β βββ tools.py # Chat, translate, OCR, itinerary, image proxy
β β βββ voice.py # TTS synthesis & speech-to-text
β β βββ documents.py # Document data models & enums
β β βββ documents_routes.py # Vault CRUD API (upload/download/delete)
β β βββ dashboard.py # Admin command center & analytics API
β β
β βββ services/ # Core business logic
β β βββ route_engine.py # TomTom routing, incidents, fuel & COβ math
β β βββ prediction_engine.py # Weather + AQI + Gemini risk calculator
β β βββ planner_engine.py # Gemini itinerary generator with retry shield
β β βββ stay_engine.py # Weather-aware stay risk scoring
β β βββ documents_engine.py # Full vault lifecycle (AI + encryption + storage)
β β βββ image_service.py # Unsplash destination image fetcher
β β
β βββ utils/ # Shared utilities
β β βββ security_utils.py # SecurityManager (Fernet, AES-256, checksums)
β β βββ data_manager.py # JSON metadata CRUD, audit logging, statistics
β β βββ firebase_admin.py # Firebase Admin SDK initialization helper
β β βββ firebase_auth.py # Firebase authentication utilities
β β βββ jwt_helper.py # JWT token utilities
β β βββ risk_logic.py # Basic speed/distance risk heuristics
β β
β βββ models/ # Data models
β βββ user.py # User model
β βββ stay.py # Stay model
β
βββ frontend/
β βββ index.html # Main application gateway
β βββ route.html # Route planning & navigation interface
β βββ prediction.html # Environmental risk prediction dashboard
β βββ planner.html # AI trip planner interface
β βββ stays.html # Stay safety analysis interface
β βββ documents.html # Secure document vault interface
β βββ tools.html # AI toolkit (chat, translate, OCR)
β βββ dashboard.html # User dashboard
β βββ admin.html # Admin command center
β βββ package.html # Travel package explorer
β βββ login.html # Authentication - login
β βββ signup.html # Authentication - registration
β βββ navbar.html # Shared navigation component
β βββ 404.html # Offline fallback page
β βββ sw.js # Service Worker (Stale-While-Revalidate)
β βββ service-worker.js # Service Worker (alternate registration)
β βββ manifest.json # PWA manifest (icons, theme, display)
β βββ capacitor.config.json # Capacitor native mobile bridge config
β βββ config.example.js # Frontend config template (API keys)
β β
β βββ js/ # Frontend logic modules
β β βββ route-core.js # Core routing logic & map rendering
β β βββ route-premium.js # Premium route features
β β βββ prediction.js # Risk prediction UI logic
β β βββ planner.js # AI planner UI logic
β β βββ stays.js # Stay analysis UI logic
β β βββ vault.js # Document vault UI logic
β β βββ tools.js # AI toolkit UI logic
β β βββ dashboard.js # Dashboard UI logic
β β βββ admin-dashboard.js # Admin command center UI
β β βββ package.js # Travel packages UI
β β βββ auth.js # Firebase authentication logic
β β βββ firebase.js # Firebase SDK initialization
β β βββ navbar.js # Navigation component logic
β β βββ bg-canvas.js # Background canvas animations
β β βββ translation.js # Translation module
β β βββ voice-alerts.js # Voice alert & TTS controller
β β βββ service-worker.js # Service worker registration
β β
β βββ css/ # Stylesheets
β β βββ style.css # Global design tokens
β β βββ auth.css # Authentication pages
β β βββ dashboard.css # Dashboard styles
β β βββ route.css # Route planner styles
β β βββ prediction.css # Prediction dashboard styles
β β βββ planner.css # AI planner styles
β β βββ stays.css # Stay analysis styles
β β βββ vault.css # Document vault styles
β β βββ tools.css # AI toolkit styles
β β βββ package.css # Travel package styles
β β βββ navbar.css # Navigation styles
β β βββ admin-analytics.css # Admin dashboard styles
β β
β βββ assets/ # Static media assets
β βββ icon-192.png # PWA icon (192Γ192)
β
βββ firebase.json # Firebase Hosting configuration
βββ .firebaserc # Firebase project alias
βββ requirements.txt # Root-level Python dependencies
βββ .gitignore # Git exclusion rules
- Python 3.10+
- Node.js 16+ (optional, for Capacitor builds)
- Git
git clone https://github.com/mohamad-shafeez/SafeNav.git
cd SafeNav# Create and activate a virtual environment
python -m venv backend/venv
source backend/venv/bin/activate # macOS/Linux
backend\venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txtCreate a .env file in the backend/ directory:
# --- AI Engine ---
GOOGLE_API_KEY=your_gemini_api_key
GEMINI_API_KEY=your_gemini_api_key_backup
PLANNER_API_KEY=your_planner_gemini_key
# --- Navigation ---
TOMTOM_API_KEY=your_tomtom_api_key
# --- Environmental Data ---
OPENWEATHER_API_KEY=your_openweathermap_key
AQI_TOKEN=your_waqi_token
# --- Image Service ---
UNSPLASH_ACCESS_KEY=your_unsplash_key
# --- Firebase ---
FIREBASE_PROJECT_ID=your_firebase_project_id
# --- App ---
SECRET_KEY=your_flask_secret_keyPlace your serviceAccountKey.json in the backend/ directory for Firebase Admin SDK initialization. Without it, the app falls back to project IDβbased initialization.
# Copy the config template
cp frontend/config.example.js frontend/config.js
# Edit config.js with your API keyspython backend/app.pyThe API server will start at http://127.0.0.1:5000.
Open frontend/index.html in your browser, or deploy via Firebase Hosting:
firebase deploy --only hosting| Variable | Service | Required | Description |
|---|---|---|---|
GOOGLE_API_KEY |
Gemini AI | β | Primary Gemini API key for prediction & directives |
GEMINI_API_KEY |
Gemini AI | β‘ | Backup key for retry shield rotation |
PLANNER_API_KEY |
Gemini AI | β‘ | Dedicated key for itinerary generation |
TOMTOM_API_KEY |
TomTom | β | Routing, traffic, and incident data |
OPENWEATHER_API_KEY |
OpenWeatherMap | β | Real-time weather data |
AQI_TOKEN |
WAQI | β | Air Quality Index data |
UNSPLASH_ACCESS_KEY |
Unsplash | β‘ | Destination imagery |
FIREBASE_PROJECT_ID |
Firebase | β‘ | Fallback if serviceAccountKey.json is missing |
SECRET_KEY |
Flask | β‘ | Flask session secret key |
β = Required for core functionality Β Β β‘ = Optional / Fallback
GET /api/health
POST /api/prediction/predict
| Field | Type | Default | Description |
|---|---|---|---|
lat |
float | β | Latitude (required) |
lng |
float | β | Longitude (required) |
time |
string | "day" |
Time of day (day / night) |
travel_mode |
string | "walking" |
Mode of travel |
user_profile |
string | "standard" |
Health profile |
duration_mins |
int | 30 |
Exposure duration in minutes |
POST /api/route/calculate
POST /api/route/multiple-routes
POST /api/route/route-analytics
POST /api/route/route-safety
POST /api/route/route-cost
POST /api/route/route-weather
POST /api/route/real-time-update
POST /api/route/optimize-route
POST /api/route/analyze
GET /api/route/health
POST /api/planner/generate
POST /api/stays/analyze
POST /api/chat
POST /api/translate
POST /api/analyze-image
POST /api/generate-itinerary
POST /api/translate-doc
GET /api/get-image?query={destination}
POST /api/voice/speak
POST /api/voice/analyze-speech
POST /api/documents/upload
GET /api/documents/list
GET /api/documents/download/{doc_id}
DELETE /api/documents/delete/{doc_id}
PATCH /api/documents/update/{doc_id}
GET /api/documents/statistics
GET /api/documents/export/summary
POST /api/admin/user-action
POST /api/admin/vault-purge
POST /api/admin/vault-update
POST /api/admin/kill-switch
POST /api/admin/track-event
GET /api/admin/analytics/system-health
GET /api/admin/analytics/audit-logs
GET /api/admin/analytics/users
GET /api/admin/analytics/health-profiles
GET /api/admin/analytics/api-quota
GET /api/admin/analytics/routes-today
GET /api/admin/analytics/recent-activity
The production backend is hosted on Render at safenav-18sk.onrender.com. The app is served via Gunicorn:
gunicorn backend.app:app --bind 0.0.0.0:$PORTConfigured via backend/vercel.json using @vercel/python runtime. All requests are routed to app.py.
firebase deploy --only hostingThe firebase.json serves the frontend/ directory as the public root.
| Strategy | Implementation |
|---|---|
| API Retry Shield | Exponential backoff with key rotation for Gemini 429/503 errors |
| Graceful Degradation | Cached/fallback values when external APIs are unreachable |
| Score Clamping | Safety scores capped at 150 to prevent extreme fluctuations |
| Firebase Fallback | Project IDβbased init when serviceAccountKey.json is absent |
| Offline PWA | Service Worker serves cached app shell; 404 page for navigation failures |
| Database Recovery | Automatic backup restoration when metadata.json is corrupted |
| Audit Trail | All admin actions logged to Firestore with immutable timestamps |
- Encryption β Fernet (AES-256-CBC) with PBKDF2-HMAC-SHA256 key derivation
- Key Management β Auto-generated keys with timestamped backup rotation
- Data Integrity β SHA-256 checksums on all encrypted documents
- Authentication β Firebase Auth with JWT token verification on all admin endpoints
- Admin Whitelist β Hardcoded email allowlist for admin access (backend-enforced)
- CORS β Configured per-blueprint with wildcard restriction on production
- Secrets β All API keys, service account files, and encryption keys excluded via
.gitignore
Exposure Multiplier = min(2.0, max(1.0, duration_mins / 30))
Score += (50 Γ multiplier) if real_feel > adaptive_heat_limit
Score += (40 Γ multiplier) if AQI > profile_threshold
Score += (15 Γ multiplier) if walking in extreme conditions
Score += 10 if nighttime
Fuel (L) = Ξ£ (segment_km / 100) Γ road_type_rate
COβ (kg) = Fuel Γ 2.31 kg/L
Cost ($) = Fuel Γ price + Toll + Maintenance (0.05/km) + Depreciation (0.10/km)
Base = 85
β5 if distance > 100 km
β2n for each complex maneuver (roundabouts, forks)
Clamped to [0, 100]
This project was developed as a Final Year Project (FYP).
Built with β€οΈ by Mohamad Shafeez