Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Dockerfile.backend
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ WORKDIR /app
COPY requirements.txt .
COPY backend/requirements.txt backend/requirements.txt
COPY earnings/earnings/requirements.txt earnings/earnings/requirements.txt
COPY drivepulse_stress_model/requirements.txt drivepulse_stress_model/requirements.txt
COPY driveintel_stress_model/requirements.txt driveintel_stress_model/requirements.txt

# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt \
&& pip install --no-cache-dir -r backend/requirements.txt \
&& pip install --no-cache-dir -r earnings/earnings/requirements.txt \
&& pip install --no-cache-dir -r drivepulse_stress_model/requirements.txt
&& pip install --no-cache-dir -r driveintel_stress_model/requirements.txt

# Copy source code
COPY backend/ backend/
COPY earnings/ earnings/
COPY drivepulse_stress_model/ drivepulse_stress_model/
COPY driveintel_stress_model/ driveintel_stress_model/

ENV PYTHONUNBUFFERED=1

Expand Down
2 changes: 1 addition & 1 deletion Procfile
Original file line number Diff line number Diff line change
@@ -1 +1 @@
web: uvicorn backend.main:app --host 0.0.0.0 --port ${PORT:-8000}
web: sh -c "cd backend && uvicorn main:app --host 0.0.0.0 --port ${PORT:-8000}"
228 changes: 106 additions & 122 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,168 +1,152 @@
# Driver Pulse: Team ACE
# DriverIntel: Advanced Driver Safety & Behavior Analytics

- **Demo Video:** https://youtu.be/PL-XsfVfLA0?feature=shared
- **Live Application:** https://driver-pulse-gamma.vercel.app/
<div align="center">
<p><strong>A state-of-the-art Web Application designed to improve driver safety, behavior, and efficiency in the ride-hailing industry through Artificial Intelligence.</strong></p>
</div>

- **Judge Login Credentials:**
Username: judge@uber.com
Password: hackathon2026
---

## 🚀 Welcome to DriverIntel

**DriverIntel** is a real-time driver safety & behavior analytics platform built exclusively for ride-hailing drivers. By leveraging on-device sensor data (accelerometer, gyroscope, and microphone) via Machine Learning (ML) models, it detects stressful driving situations, analyzes dangerous behavior patterns, and provides highly personalized safety coaching—all wrapped in a stunning, premium dark-themed glassmorphic user interface.

- **Live Application:** [DriverIntel Alpha Vercel](https://driveintel-alpha.vercel.app/)
- **Demo Video:** [YouTube Demo](https://youtu.be/PL-XsfVfLA0?feature=shared)

**Demo Credentials:**
> **Username:** `demo@driveintel.com`
> **Password:** `demo2026`

- **Note to Judges:** The backend is hosted on Render and may take around 60 seconds to wake up on the first request.
---

## ✨ Core Features

DriverIntel provides a complete suite of powerful tools designed for both individual drivers and ride-hailing platform analysts:

Real-time driver wellness & earnings intelligence platform for ride-hailing drivers. Uses on-device sensor data (accelerometer, gyroscope, microphone) with ML models to detect stressful driving situations and forecast earnings velocity.
* **📊 Dynamic Dashboard** — Get a comprehensive daily trip overview, your overall safety score, a stress event timeline, and high-level behavior insights at a glance.
* **🗺️ Interactive Trip Mapping** — **Risk along route:** Leaflet maps with dynamically severity-colored route segments based on live event timestamps. Includes playback cursors and rich popups explaining the severity, model confidence, and safety logic.
* **📈 Advanced Trends** — Understand your driving behavior over time with weekly/monthly patterns, fatigue tracking, and stress event analytics.
* **🎯 Goal Tracking** — Improve your daily safety by setting, committing to, and tracking behavioral modifications (e.g., reduce harsh braking, defensive driving).
* **🔮 Predict & Preview** — Enter raw sensor telemetry for instant stress prediction. Also features a preview Map with high-risk geographical zones.
* **📁 Batch Processing** — Built for analysts. Upload a CSV of multi-driver telemetry and run large-scale inference simultaneously for macro-level safety analysis.
* **🤖 AI Co-Pilot Assistant** — An integrated, context-aware AI Safety Assistant (powered by Google Gemini) ready to provide interactive, personalized coaching and guidance on demand.
* **🔍 Explainable AI (XAI)** — Understand *why* an event was flagged. DriverIntel provides per-event feature contributions (e.g., high lateral acceleration) and model confidence percentages.

---

## Features
## 🎨 Premium UI/UX

- **Dashboard** — Daily trips, earnings, stress score, timeline
- **Trip Detail** — Map playback, sensor charts, event detection with explainability
- **Trends** — Weekly/monthly earnings, stress, and velocity charts
- **Goals** — Set and track daily earnings targets
- **Predict** — Enter sensor/earnings values → instant ML prediction *(judge-facing)*
- **Batch Upload** — Upload CSV → run inference on multiple trips at once *(judge-facing)*
- **Explainability** — Per-event feature contributions, confidence badges
- **Feedback** — Thumbs up/down on detected events
- **Auth** — Login / register with demo accounts or new profile
DriverIntel utilizes a custom **High-Contrast Dark Glassmorphism** design language.
The entire application was built iteratively to reflect an ultra-modern aesthetic standard using Tailwind CSS:

To log **multiple trips at once**, go to the `Trips` tab and use **Import CSV**.
* **Vibrant Gradients over Deep Backgrounds** (`slate-950` / `slate-900`)
* **Translucent Frosted Glass** layered panels (`backdrop-blur-xl`, `bg-white/5` borders)
* **Sleek Micro-animations**, customized chart tooltips, and dynamic states
* Zero legacy light-mode elements—providing drivers with maximum visibility, luxury, and eye comfort even during late-night shifts.

---

## Architecture
## 🏗️ Architecture

DriverIntel uses a robust split architecture designed for performance and scale.

```mermaid
flowchart LR
UI[Frontend: React 18, Vite, Tailwind]
API[Backend: FastAPI, Uvicorn, Python]
DB[(In-Memory Trips / Data Store)]
ML[Stress ML Inference Engine]
AI[AI Safety Assistant / Gemini]

UI <==>|JSON via /api/*| API
API <--> DB
API <--> ML
API <--> AI
```
Driver-Pulse/
├── backend/ # FastAPI REST API (25 endpoints)
│ ├── main.py # Routes, middleware, Pydantic models
│ ├── data/
│ │ ├── sample_data.py # Synthetic trip/route/event generator
│ │ ├── batch_processor.py # Loads ML models, runs batch inference
│ │ ├── trips_import.py # CSV trip import parser
│ │ ├── users.py # In-memory auth store
│ │ └── config.py # Batch limits & constants
│ └── utils/
│ └── logging.py # Timestamped structured logging

### Folder Structure
```text
DriverIntel/
├── backend/ # FastAPI REST API
│ ├── main.py # Core routing and controllers
│ ├── agent.py # LLM Integration (AI Safety Assistant)
│ └── data/ # Batch Processing, Import handling, config
├── frontend/ # React 18 + Vite + Tailwind SPA
│ └── src/
│ ├── pages/ # 8 pages: Home, Dashboard, Trips, TripDetail,
│ │ # Trends, Goals, Predict, BatchUpload
│ ├── components/ # 16 reusable components
│ ├── api/client.js # Centralised API client
│ └── utils/sanityChecks.js # Input validation helpers
├── drivepulse_stress_model/ # Stress Detection ML pipeline
│ ├── run.py # CLI entry (--generate --calibrate --train --demo)
│ ├── src/
│ │ ├── generate_data.py # Synthetic sensor window generator (3,150 samples)
│ │ ├── train.py # RF classifier training + evaluation
│ │ ├── inference.py # InferenceEngine with rule-based fallback
│ │ └── hal.py # Hardware Abstraction Layer (device calibration)
│ ├── model/ # Trained artifacts (rf_model.pkl, baselines, contract)
│ └── calibration/ # Device calibration profile
├── earnings/earnings/ # Earnings Forecasting ML pipeline
│ ├── run.py # Sequential pipeline entry
│ ├── src/
│ │ ├── build_dataset.py # Merges drivers + goals + velocity + trips
│ │ ├── features.py # 14-feature engineering (lags, rolling avg, rush flags)
│ │ ├── augment.py # 5× Gaussian noise augmentation
│ │ ├── train.py # RF regressor training + evaluation
│ │ └── inference.py # Batch velocity prediction
│ ├── model/ # Trained artifacts (rf_model.pkl, contract)
│ └── data/ # Source CSVs (drivers, goals, velocity, trips)
├── streamlit_app.py # Standalone Streamlit demo (3 tabs)
├── tests/data/ # Example CSVs for batch & import testing
└── requirements.txt # Root Python dependencies
│ ├── pages/ # Full Page Views (Dashboard, Predict, etc.)
│ ├── components/ # Reusable UI (Leaflet Maps, Charts, Copilot)
│ ├── api/ # Centralized application client
├── driveintel_stress_model/ # ML Pipeline for Stress Detection
│ ├── src/ # Random Forest training, XAI logic
│ └── model/ # Artifacts (.pkl)
└── streamlit_app.py # Standalone Streamlit rapid diagnostic tool
```

```mermaid
flowchart LR
browser[Browser_ReactApp] --> api[FastAPI_Backend]
api --> tripsStore[InMemory_Trips_+_Goals]
api --> stressBatch[Stress_Batch_Processor]
api --> earningsBatch[Earnings_Batch_Processor]
stressBatch --> stressModel[Stress_Model_Files]
earningsBatch --> earningsModel[Earnings_Model_Files]
```
---

## 💻 Tech Stack

| Layer | Technologies |
|-------|------|
| **Frontend** | React 18, Vite, Tailwind CSS, Recharts, Leaflet, Lucide Icons |
| **Backend** | Python 3.9+, FastAPI, Uvicorn, Pydantic |
| **AI / ML** | Scikit-Learn, Pandas, NumPy, Google Gemini API |
| **Deploy Target**| Vercel (Frontend Component) & Render (Backend Service) |

---

## Setup
## 🛠️ Setup & Local Development

### Prerequisites
- Python 3.9+
- Node.js 18+
- Docker Desktop (for judge-friendly containerisation)

### Install & Run (local dev)
### 1. Install & Run Directly

Start the backend:
```bash
# Install Python dependencies
pip install -r requirements.txt

# Start backend (http://localhost:8000)
cd backend && python main.py

# In a new terminal — start frontend (http://localhost:5173)
cd frontend && npm install && npm run dev
cd backend
pip install -r ../requirements.txt
python main.py
```
*(Runs on `http://localhost:8000`)*

Open **http://localhost:5173** in your browser.

---
Start the frontend:
```bash
cd frontend
npm install
npm run dev
```
*(Runs on `http://localhost:5173`)*

### Run with Docker
Open **http://localhost:5173** to use the application.

With [Docker Desktop](https://www.docker.com/products/docker-desktop/) running:
### 2. Run via Docker Compose

```bash
# From the repo root (Driver-Pulse/)
# Navigate to repository root
docker compose up --build
```

Then open:

- Frontend: `http://localhost:5173`
- Backend (direct): `http://localhost:8000/api/health`

The frontend talks to the backend via `/api/*`, which is proxied by Nginx inside the `frontend` container to the `backend` container.

**Judge login (demo account):**

- Username: `judge@uber.com`
- Password: `hackathon2026`
Then visit `http://localhost:5173`! All API calls are locally proxied by NGINX inside the container.

---

## Tech Stack
## 🔮 Roadmap (Next Steps)

| Layer | Tech |
|-------|------|
| Frontend | React 18, Vite, Tailwind CSS, Recharts, Leaflet |
| Backend | FastAPI, Uvicorn |
| ML | scikit-learn, NumPy, Pandas |
* [ ] **Predictive High-Risk Routing** — Seamless integration of the *Predict* UI with production historical accident dataset grids for live hazard routing.
* [ ] **In-Trip Voice Coaching** — Expand the AI Assistant into an active voice companion that speaks safely contextualized warnings.
* [ ] **Telematics Database Integration** — Migrate the in-memory data store to a production-ready PostgreSQL instance with PostGIS for geo-queries.

---

## Data Flow
## 🤝 Contributing

- **Trips & goals**: Manual entry or CSV import hit `/api/trips` or `/api/trips/import-csv`, which update an in-memory trips list. Goals (`/api/goals`) and dashboard (`/api/dashboard`) recompute current earnings, hours, and forecast from those trips.
- **Batch stress & earnings**: Batch CSV uploads are processed by backend helpers that engineer features, call local models, and return per-row predictions plus summaries as JSON.

---

## Scalability & Modularity

- **Backend**: FastAPI routes in `backend/main.py` delegate to small modules in `backend/data/` for trips, goals, imports, and batch processing, so swapping the in-memory store for a database or separate ML service is a local change.
- **Frontend**: The React app uses a single API client layer (`frontend/src/api/client.js`) plus page/component separation, making it easy to plug in global state, auth, or feature flags without rewriting screens.
- **Batch endpoints**: Batch CSV processing is stateless per request, so multiple backend instances can handle uploads in parallel behind a load balancer.

---
This prototype was built with a vision for safer streets. We highly encourage contributions!
Feel free to fork the repository, cut a feature branch, and submit a PR for review.

## Testing & Validation Notes
## 📄 License
This project operates under the **MIT License**. Refer to `LICENSE` for exact specifications.

- **Frontend sanity checks** — lightweight helpers in `frontend/src/utils/sanityChecks.js` validate money inputs, time ranges, and clamp goal targets.
- **Example test files** — illustrative, non-wired tests live in `frontend/src/__tests__/` (e.g. `EarningsProgress.test.jsx`, `TripsAddTrip.test.jsx`) to show how key components and behaviours could be validated in a full test setup.
<div align="center">
<sub>Built for the future of Ride-Hailing.</sub>
</div>
11 changes: 5 additions & 6 deletions backend/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import google.generativeai as genai
from dotenv import load_dotenv
# Add get_profile to your imports
from backend.data.sample_data import (
from data.sample_data import (
get_trips,
get_goals,
get_profile, # <--- Added this
Expand Down Expand Up @@ -61,16 +61,15 @@ def run_co_pilot(user_prompt: str):
model_name='models/gemini-flash-latest',
tools=[get_navigation_assistant],
system_instruction=(
f"You are the DrivePulse AI Co-pilot. You are assisting {driver_name}."
f"You are the DriveIntel Safety Assistant. You are assisting {driver_name}."
"\n\nSTRICT OPERATING PROCEDURES:\n"
"1. IDENTITY: Your name is 'DrivePulse Co-pilot'. Never call yourself Alex. "
"1. IDENTITY: Your name is 'DriveIntel Safety Assistant'. "
"Address the driver as 'Alex' or 'Partner' when appropriate."
"\n2. GOALS: Mention the daily earnings target (₹1,800) only if Alex asks about "
"money, performance, or 'how am I doing?'. Don't bring it up unprompted."
"\n2. BEHAVIOR INSIGHTS: Provide personalized safety tips and behavior analysis based on their trip data."
"\n3. NAVIGATION: Use the get_navigation_assistant tool for food/break requests. "
"Suggest Mumbai-based spots and ask before providing the navigation link."
"\n4. LINK FORMATTING: Use the [Start Navigation](URL) format only when Alex says yes."
"\n5. TONE: Professional, efficient, and supportive. Use ₹ for all currency."
"\n5. TONE: Professional, efficient, and supportive. Focus on driver safety and behavior improvement."
)
)

Expand Down
Loading