diff --git a/README.md b/README.md index ab8472e..a9e218b 100644 --- a/README.md +++ b/README.md @@ -1,207 +1,152 @@ -# DriveIntel: Driver Safety & Behavior Analytics +# DriverIntel: Advanced Driver Safety & Behavior Analytics -- **Demo Video:** https://youtu.be/PL-XsfVfLA0?feature=shared -- **Live Application:** https://driveintel-alpha.vercel.app/ - -- **Demo Login Credentials:** - Username: demo@driveintel.com - Password: demo2026 - -- **Note:** This is a prototype platform. Backend features behavior detection and safety analysis. - -Real-time driver safety & behavior analytics platform for ride-hailing drivers. Uses on-device sensor data (accelerometer, gyroscope, microphone) with ML models to detect stressful driving situations, analyze driver behaviors, and provide personalized safety insights. +
+

A state-of-the-art Web Application designed to improve driver safety, behavior, and efficiency in the ride-hailing industry through Artificial Intelligence.

+
--- -## Features - -- **Dashboard** — Daily trip overview, safety score, stress event timeline, behavior insights -- **Trip Detail** — **Risk along route**: Leaflet map with severity-colored route segments (from event timestamps), legend, playback cursor, and rich popups (severity, confidence, explain summary); sensor charts and stress event explainability -- **Trends** — Weekly/monthly driver behavior patterns, stress event analytics -- **Safety Goals** — Set and track safety improvements (e.g., reduce high-stress events) -- **Predict** — Enter sensor values → instant stress prediction *(analyst-facing)*; **demo high-risk zones map** (illustrative Leaflet circles over Bangalore — not live incident data) -- **Batch Upload** — Upload CSV → run inference on multiple trips at once *(analyst-facing)* -- **Explainability** — Per-event feature contributions, confidence badges -- **Feedback** — Thumbs up/down on detected events for model improvement -- **Auth** — Login / register with demo accounts or new profile -- **AI Safety Assistant** — DriveIntel Co-pilot for personalized safety tips & guidance - -To analyze **multiple trips at once**, go to the `Trips` tab and use **Import CSV**. - ---- +## 🚀 Welcome to DriverIntel -## Architecture +**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. -``` -DriveIntel/ -├── backend/ # FastAPI REST API (25 endpoints) -│ ├── main.py # Routes, middleware, Pydantic models -│ ├── agent.py # AI Safety Assistant integration -│ ├── data/ -│ │ ├── sample_data.py # Synthetic trip/event generator -│ │ ├── batch_processor.py # Loads stress 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 -│ -├── frontend/ # React 18 + Vite + Tailwind SPA -│ └── src/ -│ ├── pages/ # 8 pages: Home, Dashboard, Trips, TripDetail, -│ │ # Trends, Safety Goals, Predict, BatchUpload -│ ├── components/ # Reusable UI + TripMap (risk-colored route), RiskZonesPreviewMap (demo zones) -│ ├── api/client.js # Centralised API client -│ └── utils/sanityChecks.js # Input validation helpers -│ -├── driveintel_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/ # [DEPRECATED] Earnings Forecasting ML pipeline -│ ├── README.md # See legacy documentation -│ └── ... -│ -├── streamlit_app.py # Standalone Streamlit demo (stress detection focus) -├── tests/data/ # Example CSVs for batch & import testing -└── requirements.txt # Root Python dependencies -``` +- **Live Application:** [DriverIntel Alpha Vercel](https://driveintel-alpha.vercel.app/) +- **Demo Video:** [YouTube Demo](https://youtu.be/PL-XsfVfLA0?feature=shared) -```mermaid -flowchart LR - browser[Browser_ReactApp] --> api[FastAPI_Backend] - api --> tripsStore[InMemory_Trips_+_Goals] - api --> stressBatch[Stress_Batch_Processor] - stressBatch --> stressModel[Stress_Model_Files] - api --> assistant[AI_Safety_Assistant] -``` +**Demo Credentials:** +> **Username:** `demo@driveintel.com` +> **Password:** `demo2026` --- -## Setup +## ✨ Core Features -### Prerequisites -- Python 3.9+ -- Node.js 18+ - - Docker Desktop (for judge-friendly containerisation) +DriverIntel provides a complete suite of powerful tools designed for both individual drivers and ride-hailing platform analysts: -### Install & Run (local dev) - -```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 -``` - -Open **http://localhost:5173** in your browser. +* **📊 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. --- -### Run with Docker - -With [Docker Desktop](https://www.docker.com/products/docker-desktop/) running: - -```bash -# From the repo root (DriveIntel/) -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. +## 🎨 Premium UI/UX -**Demo login (sample account):** +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: -- Username: `demo@driveintel.com` -- Password: `demo2026` +* **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. --- -## Tech Stack - -| Layer | Tech | -|-------|------| -| Frontend | React 18, Vite, Tailwind CSS, Recharts, Leaflet | -| Backend | FastAPI, Uvicorn, Pydantic | -| ML | scikit-learn, NumPy, Pandas | -| Deployment | Vercel (frontend), Render (backend) | - -### Hosted split deploy (Vercel + Render) +## 🏗️ Architecture -**Option A — Vercel rewrites (simplest for the whole app):** proxy `/api/*` to your Render service so every relative `fetch('/api/...')` still works. Example `vercel.json` at the repo root or frontend root: +DriverIntel uses a robust split architecture designed for performance and scale. -```json -{ - "rewrites": [ - { "source": "/api/:path*", "destination": "https://YOUR-RENDER-SERVICE.onrender.com/api/:path*" } - ] -} +```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 ``` -**Option B — `VITE_API_BASE`:** the shared client in [`frontend/src/api/client.js`](frontend/src/api/client.js) uses `import.meta.env.VITE_API_BASE || '/api'`. Set at build time on Vercel to your backend API prefix, e.g. `https://YOUR-RENDER-SERVICE.onrender.com/api`. Note: any **direct** `fetch('/api/...')` in pages (e.g. auth on Home, features on Predict) still needs rewrites unless you point those at the same base. +### 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/ # 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 +``` --- -## Data Flow +## 💻 Tech Stack -- **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 metrics, stress events, and safety scores from those trips. -- **Batch stress inference**: Batch CSV uploads are processed by backend helpers that engineer features, call the local stress model, and return per-row predictions and summaries as JSON. -- **Risk visualization**: Trip detail maps use each event’s `offset_sec` and trip duration to split the polyline into segments: calm stretches vs low/medium/high severity approaching each detected event. Markers reuse backend `location`, `severity`, and `explain.summary` for popups. +| 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) | --- -## Scalability & Modularity +## 🛠️ Setup & Local Development -- **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. -- **AI Safety Assistant**: Integrates Google's Gemini API for intelligent, personalized driver guidance within the safety framework. +### Prerequisites +- Python 3.9+ +- Node.js 18+ ---- +### 1. Install & Run Directly -## Testing & Validation Notes +Start the backend: +```bash +cd backend +pip install -r ../requirements.txt +python main.py +``` +*(Runs on `http://localhost:8000`)* -- **Frontend sanity checks** — lightweight helpers in `frontend/src/utils/sanityChecks.js` validate time ranges and inputs. -- **Example test files** — illustrative tests live in `frontend/src/__tests__/` (e.g., `TripsAddTrip.test.jsx`) to show how key components and behaviors could be validated in a full test setup. +Start the frontend: +```bash +cd frontend +npm install +npm run dev +``` +*(Runs on `http://localhost:5173`)* ---- +Open **http://localhost:5173** to use the application. -## Future Roadmap (Prototype Phase) +### 2. Run via Docker Compose -### Coming Soon: -- 🚨 **Production high-risk routing** — The **Predict** page includes a **demo** map (illustrative zones only). A future release would connect real historical accident or incident datasets and live routing warnings. -- 📊 **Real-time Driver Coaching** — In-trip feedback on driving behavior with immediate tips for improvement. -- 🔔 **Smart Alerts** — Predictive notifications about risky traffic conditions ahead. -- 🌍 **Multi-city Expansion** — Support for more cities beyond Mumbai, with localized behavior analytics. +```bash +# Navigate to repository root +docker compose up --build +``` +Then visit `http://localhost:5173`! All API calls are locally proxied by NGINX inside the container. --- -## Contributing +## 🔮 Roadmap (Next Steps) -This is a prototype platform built for the Uber Hackathon. Contributions are welcome. Please fork, create a feature branch, and submit a pull request. +* [ ] **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. --- -## License - -MIT License. See LICENSE file for details. +## 🤝 Contributing ---- +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. -## Support +## 📄 License +This project operates under the **MIT License**. Refer to `LICENSE` for exact specifications. -For issues or questions, please file an issue on GitHub or contact the development team. +
+ Built for the future of Ride-Hailing. +
diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000..dfb18f1 --- /dev/null +++ b/backend/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "backend", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/backend/requirements.txt b/backend/requirements.txt index c173067..3b69eff 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,13 +1,14 @@ -fastapi>=0.104 -uvicorn>=0.24 -pydantic>=2.0 -python-multipart>=0.0.6 -numpy>=1.24.0 pandas>=2.0.0 +numpy>=1.24.0 scikit-learn>=1.3.0 joblib>=1.3.0 +streamlit>=1.28.0 +fastapi>=0.104 +uvicorn>=0.24 +pydantic>=2.0 python-dateutil>=2.8 +python-multipart>=0.0.6 + -# --- AI Co-pilot Additions --- -google-generativeai>=0.8.0 -python-dotenv>=1.0.0 \ No newline at end of file +google-generativeai +python-dotenv \ No newline at end of file diff --git a/docs/PROGRESS_LOG.md b/docs/PROGRESS_LOG.md deleted file mode 100644 index d53e431..0000000 --- a/docs/PROGRESS_LOG.md +++ /dev/null @@ -1,29 +0,0 @@ -# Progress Log (Development History) - -A chronological log of our problem-solving process and major iterations. - - ---- - -**Mar 4:** Project kickoff. Team discussion on requirements, user persona, and value proposition. Decided on stress + earnings as dual focus. - -**Mar 5:** Finalized tech stack (FastAPI, React, scikit-learn). Planned architecture and repo structure. Set up the project repository and initial folder structure. - -**Mar 6:** Backend development: implemented API skeleton (trips, goals, dashboard), created synthetic trip data generator, and batch processor. - -**Mar 7:** Backend ML: built and trained initial stress detection (RF, HAL, Platt calibration) and earnings velocity models. Added endpoints for batch inference and CSV import. - -**Mar 8:** Frontend development: built dashboard, trip list, trip detail, earnings progress bar. Integrated backend APIs. Added batch upload and explainability features. - -**Mar 9:** Documentation: wrote design doc (HTML), architecture diagram (SVG), and progress log. Re-checked all features, tested flows, and made final edits based on feedback. Prepared for deployment. - -**Mar 10:** Deployment and submission: added Dockerised deployment (FastAPI + React via Nginx, `docker-compose.yml` at repo root), verified end-to-end flows in containers, and documented judge login plus Docker run instructions in all README/docs before final submission. - -**Later iteration:** Risk-focused map UX — Trip Detail **Risk along route** map (`TripMap.jsx`) with severity-colored polylines from event `offset_sec`, in-map legend, escaped rich popups, and high-severity marker styling; **Predict** page **demo** high-risk zones (`RiskZonesPreviewMap.jsx`, illustrative Bangalore circles only). README and HTML docs updated to describe behaviour, `VITE_API_BASE` for Vercel, and roadmap wording (demo vs production routing). - ---- - -**Outcome:** -Successfully built and deployed DrivePulse — a driver safety and earnings intelligence platform that transforms raw trip signals into actionable insights. The system combines real-time stress detection with earnings velocity forecasting while maintaining privacy through on-device processing. All core features (stress detection, earnings forecasting, explainability tools, batch testing, and feedback collection) were implemented as planned. Documentation, architecture diagrams, and progress logs were completed and the project was submitted on time. - ---- \ No newline at end of file diff --git a/docs/architecture_explanation.html b/docs/architecture_explanation.html index 7fbad12..0f98527 100644 --- a/docs/architecture_explanation.html +++ b/docs/architecture_explanation.html @@ -3,69 +3,77 @@ - DrivePulse — System Architecture + DriverIntel — System Architecture
-

🚗 DrivePulse

-

System Architecture

-
UBER SHE++ HACKATHON 2026
-
MerinRishitLavisha
+

🚗 DriverIntel

+

System Architecture & Platform Design

+
Driver Safety Analytics Platform
@@ -73,157 +81,154 @@

🚗 DrivePulse

01 Architecture Diagram

-

End-to-end data flow: sensors → on-device processing → server → driver insights → feedback loop.

+

End-to-end data flow: sensors → edge processing → server API → AI Copilot → driver insights.

- + - - ON-DEVICE (EDGE) + + ON-DEVICE (EDGE) - - OFF-DEVICE (SERVER) + + OFF-DEVICE (SERVER API) - - FEEDBACK LOOP + + FEEDBACK & AI ASSISTANT - - 📱 Accelerometer + + 📱 Accelerometer 10 Hz x/y/z motion - - 🎤 Microphone + + 🎤 Microphone dB envelope only - - 📍 GPS + Speed - km/h, lat/lng + + 📍 GPS Location + lat/lng / speed - - 💰 Trip Earnings - ₹ per trip, hours + + ⏱️ Gyroscope + Rotation forces - - - + + + - - HAL Calibration - Device normalisation - AGC + road baseline + + Hardware Abstraction + Device normalisation + Signal processing - + - + Feature Extraction - 30s windows, Z-score norm - ~12 stress / 14 earnings feats - - - + 30s sliding windows + Statistical XAI factors - + - + Local ML Inference - RF Classifier (stress) · <1ms - RF Regressor (earnings) + RF Classifier (stress) · <1ms + Fallback Rules applied - - REST + + REST - + - - 🔔 Driver Alerts - Real-time, on-device + + 🔔 Driver Alerts + Real-time coaching - - 📊 Driver Dashboard - Glanceable UI - + + 📊 Driver App (React) + Glassmorphic UI + - + FastAPI Backend - 25 REST endpoints - Auth, CORS, validation + Core REST API + XAI interpretation - - Data Store - In-memory (MVP) - Trips, goals, events - + + Data Store + Trips, events + Goals, user profiles + - + Batch Processor - CSV upload → inference - Stress + Earnings models - + CSV upload → inference + Analyst stress reporting + - - Model Artifacts - rf_model.pkl (×2) - baselines, contracts - + + Model Artifacts + rf_model.pkl + Safety baselines + - + Aggregation Engine - Dashboard summaries - Trends, goal tracking - + Dashboard summaries + Driver trends metrics + - - - Driver Web App (React) - 8 pages, 16 components - Maps, charts, modals - + + + Vite / React Hosting + React 18 SPA + Tailwind CSS compilation + - - - 👍👎 Feedback - Collected per event - + + + 🤖 AI Safety Agent + Gemini LLM Integration + - - - 🔄 Retrain Loop - Future: feedback → model - + + + 🔄 Human Feedback + Thumbs up/down tracking + - - - - + + + + - DrivePulse — End-to-End Data Flow + DriverIntel — End-to-End Data Flow

Right-click → "Save image as" or screenshot this diagram to export as PNG.

@@ -232,121 +237,99 @@

01 Architecture Diagram

-

02 Architecture Explanation

-

Design decisions and engineering trade-offs.

+

02 Architecture & Engineering Design

+

Design decisions and system infrastructure.

-

Real-Time vs. Post-Trip Processing

+

Responsive UI & Glassmorphism Design

    -
  • Stress detection → real-time, on-device. RF classifier runs per 30s window in <1ms. Driver gets alerts instantly, no network needed.
  • -
  • Earnings prediction → on-device per trip. Velocity forecasting runs locally after each trip completes.
  • -
  • Aggregation → server-side. Dashboard summaries, trends, and goal tracking are computed on the server where full trip history is available.
  • -
  • Why this split? A driver in danger can't wait for a network round-trip. Safety alerts must work in tunnels and dead zones.
  • +
  • Premium Aesthetics: Built entirely with a deeply dark, frosted glassmorphism interface heavily reliant on backdrop-blur-xl utilities.
  • +
  • Performant Renderings: Built using Vite and React 18 for massive speed gains during compilation. State management handled cleanly to avoid chart re-renders.
  • +
  • Accessible UI: High-contrast tokens created in CSS ensure data visualisations are distinct for night-driving without causing fatigue.
-

Connectivity & Resilience

+

Real-Time vs. Post-Trip Processing

    -
  • Both ML models run locally — no network required for predictions.
  • -
  • Queued sync — trip data and feedback stored locally, synced when connectivity returns.
  • -
  • Rule-based fallback — if model files are missing, threshold rules (motion >3.5g + audio >80 dB → CONFLICT) keep the app functional.
  • -
  • SPA frontend — once loaded, all navigation works offline; only API data calls need network.
  • +
  • Stress detection → real-time edge processing. Random Forest classifier runs per 30s window in <1ms. Driver gets alerts directly without needing continuous API polling.
  • +
  • Aggregation → Backend server. Detailed map popups, AI XAI outputs (explainable AI summaries), and history metrics load off device.
  • +
  • Why this split? A driver in a dangerous zone cannot rely on cellular reliability. Safety telemetry logic processes locally, while reporting requires sync.
-

Battery & Resource Management

+

AI Co-Pilot & XAI Feedback

    -
  • Lightweight RF models — no GPU, <1ms inference, ~12 stress features (not hundreds).
  • -
  • 10 Hz sampling — sufficient for brakes/road events; 10× less data than high-frequency approaches.
  • -
  • 30s windows — model runs ~2×/min, not continuously.
  • -
  • dB envelope only — loudness levels, not raw audio waveforms. No FFT/spectrogram cost.
  • -
  • EMA drift correction — simple update every 10 min, not a full recalibration.
  • +
  • Explainable AI integrations — The backend automatically generates XAI "Top Features" for every identified event using feature importance arrays.
  • +
  • Integrated LLM — A Gemini-backed AI Safety Assistant takes event parameters and constructs human-readable, educational summaries of the incidents instantly.
  • +
  • Data Minimisation: The LLM handles only parsed data parameters (speeds, forces, time). Audio or geo-exact details are stripped pre-prompting for absolute privacy.
-

Privacy & Data Minimisation

+

Battery & Resource Management

    -
  • No raw audio — mic input reduced to dB aggregates on-device. No recordings leave the phone.
  • -
  • No raw sensor logs — accelerometer data consumed in 30s windows, converted to statistical features, then discarded.
  • -
  • All audio classification on-device — server never receives audio data.
  • -
  • Minimal PII — username + city + experience level. No phone number, no payment data.
  • -
  • Feedback is opt-in — only event ID + boolean. No free-text harvested.
  • +
  • Lightweight RF models — no GPU required, minimal RAM footprint, ~12 extracted hardware features instead of deep learning arrays.
  • +
  • 30s sliding windows — Telemetry model only recalculates locally a few times a minute, minimizing continuous drain.
  • +
  • dB envelope only — For privacy and size, mic data is reduced to local Db scales. Driver voice clips are definitively never transmitted.

Key Trade-offs

- - - - - + + + +
DecisionGainedGave Up
On-device inferenceZero-latency alerts, offline supportCan't use large models or cross-driver patterns
RandomForest over DLLightweight, interpretable, CPU-onlyLower accuracy on complex temporal patterns
dB envelope over raw audioPrivacy, low CPU, no storageNo speech-to-text or fine-grained analysis
In-memory store over DBZero setup for judgesNo persistence across restarts
Feedback collected, not loopedSimpler systemModel doesn't self-improve (yet)
On-device inferenceZero-latency alerts, offline supportCan't use massive parameters or cross-fleet correlations instantaneously
RandomForest over DLLightweight, interpretable, CPU-onlyLower accuracy on complex multi-temporal event chains
dB envelope over raw audioPrivacy, low CPU, zero cloud bandwidthNo immediate natural language incident classification from audio
In-memory store (MVP)Zero setup friction for deploymentsNo multi-node or persistent stability without Postgres update
-

03 Deployment & Docker

-

How a judge runs the full system in minutes.

+

03 Deployment Architecture

+

How to deploy or test the architecture.

- Hackathon requirement: Include a working Dockerfile and docker-compose.yml - so a judge can run the entire stack with a single command. DrivePulse ships two services - (FastAPI backend + React frontend) wired together behind Nginx. + Infrastructure Note: DriverIntel consists of two split services: FastAPI Python Backend + Node/React Vite Frontend. They communicate natively over REST endpoints.

Containers

    -
  • Backend container: Python 3.11 + FastAPI. Runs uvicorn main:app inside the backend/ folder so imports like from utils... and from data... match local dev. Exposes 8000 with all /api/* routes.
  • -
  • Frontend container: Builds the React SPA with Node + Vite, then serves the static dist/ bundle via Nginx on port 80. Nginx proxies any request to /api/ to the backend service.
  • -
  • Compose orchestration: docker-compose.yml in the repo root builds both images, creates a shared network, and publishes: -
      -
    • http://localhost:5173 → frontend (Nginx)
    • -
    • http://localhost:8000 → backend (FastAPI, e.g. /api/health)
    • -
    -
  • +
  • Backend container: Python 3.11 + FastAPI. Runs uvicorn main:app inside the backend/ folder to execute our ML + REST models. Exposes port 8000.
  • +
  • Frontend container: Builds the React SPA with Node + Vite, compiles Tailwind definitions, and serves the static dist/ bundle via a lightweight internal proxy router.
  • +
  • Single Orchestration: Complete configuration exists in docker-compose.yml. Running docker compose up --build constructs the necessary network bridges locally for the frontend to hit /api properly.
-

Judge Runbook

+

Testing Runbook

    -
  1. Prerequisite: Install Docker Desktop and ensure it is running.
  2. -
  3. Clone repo: git clone ... && cd Driver-Pulse
  4. -
  5. One command: - docker compose up --build from the repo root (Driver-Pulse/).
  6. -
  7. Open app: visit http://localhost:5173 in the browser - (no manual dependency installation required).
  8. +
  9. Prerequisite: Start Docker Desktop.
  10. +
  11. Launch locally: git clone ... && cd Driver-Pulse (or your repository folder).
  12. +
  13. Spin up execution: docker compose up --build.
  14. +
  15. Validate app: Open http://localhost:5173 in the browser to interact via demo telemetry accounts.
- Judge credentials: we provide a pre-populated demo account.
- Username: judge@uber.com · Password: hackathon2026. + Demo Credentials: We provide structured demo telemetry data via sample accounts.
+ Username: demo@driveintel.com · Password: demo2026.
- +
-

04 Risk Maps (Frontend)

-

Spatial view of per-trip stress events and a separate demo for “area risk” storytelling.

+

04 Risk Maps & Visualisations

+

Visual layout functionality of complex geo-spatial components.

-

TripMap — segment colouring

+

Dynamic Trip Map Segmenting

    -
  • Inputs: route (lat/lng polyline), events (with offset_sec and severity), durationSec, cursorIndex for playback.
  • -
  • Event time → index along the route; segment boundaries merge duplicate indices and pick the stronger severity. Calm segments render with reduced opacity; event-ending segments use green / amber / red.
  • -
  • Markers at ev.location with popups (escaped HTML) for label, severity, confidence %, and explain.summary when available.
  • +
  • The core TripMap.jsx component takes real coordinate polyline segments and calculates spatial risk.
  • +
  • Coloring Logic: Calm baseline data outputs partially transparent routes. If an event timestamp triggers near a location chunk, the segment opacity scales up and colors (Amber/Green/Red) directly depending on event severity.
  • +
  • Rich Modals: Clicking event pins queries the React context layout for AI Assistant XAI explanations and model parameters without page routing.
-

RiskZonesPreviewMap — Predict page

+

Risk Zones Prediction Map

    -
  • Standalone Leaflet map with fixed demo circles (Bangalore). Popups state clearly that overlays are illustrative.
  • -
  • No backend dependency; complements the stress prediction form as a UX prototype for future real-world risk layers.
  • +
  • Standalone Leaflet engine using mock overlay heat-circles to present future-state infrastructure of geographical "hazard clusters" identified by the application.
- -

Hosted SPA note

-

- For a frontend on Vercel (or similar) talking to a separate API host, the client uses VITE_API_BASE (full API prefix including /api) at build time; Docker and local dev keep the default relative /api behind Nginx or the Vite proxy. -

- + diff --git a/docs/architecture_image.png b/docs/architecture_image.png index c1bf0ab..8f1642f 100644 Binary files a/docs/architecture_image.png and b/docs/architecture_image.png differ diff --git a/docs/design.html b/docs/design.html index 41ded4d..f046998 100644 --- a/docs/design.html +++ b/docs/design.html @@ -3,76 +3,90 @@ - DrivePulse — Design Document + DriverIntel — Design Document
-

🚗 DrivePulse

+

🚗 DriverIntel

Design Document

-
UBER SHE++ HACKATHON 2026
-
MerinRishitLavisha
+
Advanced Driver Analytics
@@ -84,44 +98,47 @@

01 Product Vision

User Persona

- Full-time ride-hailing driver in an Indian metro city (Bangalore in our demo). - Drives 8–10 hours daily. Cares about two things: staying safe on chaotic roads and - hitting a daily earnings target. Not tech-savvy — needs information delivered at a glance, - not buried in charts. + Full-time ride-hailing driver in a major metro city. Drives 8–10 hours daily. Cares about two things: staying safe on chaotic roads and + hitting daily performance goals. Not deeply tech-savvy — needs information delivered at a glance, + not buried in heavy statistics.

Core Value Proposition

- DrivePulse transforms raw trip signals — accelerometer, speed, audio dB — into two actionable insights: + DriverIntel transforms raw trip signals — accelerometer, spatial GPS, audio dB — into highly actionable insights:

    -
  1. Safety alerts — Detects dangerous situations (hard braking + loud cabin, escalating conflicts) in real-time and tells the driver why each event was flagged.
  2. -
  3. Earnings forecasting — Predicts earnings velocity (₹/hr), shows whether the driver is on track to hit their daily target, and estimates time-to-goal.
  4. +
  5. Safety & Coaching alerts — Detects potentially dangerous situations via Multi-factor ML (hard braking, rough maneuvering, loud cabin) and provides instant explainable tips via AI.
  6. +
  7. Predictive Pathing — Forecasts performance and guides towards goals efficiently with dynamic visual risk mapping.

The "Glanceable" Test

- A driver can't read a dense dashboard while navigating traffic. Every screen in DrivePulse is designed to pass the 2-second glance test: + A driver can't read a dense dashboard while navigating traffic. Every screen in DriverIntel is designed to pass the 2-second glance test:

+ -
- Design principle: The driver should never have to interpret raw numbers. - Every metric is translated into a status (ahead / on_track / at_risk), a colour (green / yellow / red), - or a plain-language message. Detailed signal charts and explainability modals exist for the - Trip Detail page — but they're opt-in, not the default view. -
+ +
+

02 Overall Architecture

+

End-to-End Data Flow from Edge to Cloud Insights

+ + + DriverIntel Data Flow Diagram + +

+ The system is split into two massive segments. Edge processing runs live data locally to guarantee zero latency and complete offline persistence for immediate danger alerts. Server API routing manages batch processing overhead and syncs AI interactions where robust NLP computation is requested. +

- +
-

02 Stress Detection Algorithm

+

03 Stress Detection ML Algorithm

Lightweight signal processing, sensor fusion, and false-positive reduction.

Pipeline

@@ -130,216 +147,78 @@

Pipeline

HALDevice Norm
30s Window~12 features
Z-ScoreBaseline μ/σ
-
RF Classify→ 7 classes
-
Platt Cal→ true prob
+
RF Classify→ 7 events
+
Edge Alert→ driver

Cleaning Noisy Motion Data (HAL)

-

Phone sensors are noisy and device-dependent. Our Hardware Abstraction Layer runs a two-phase calibration:

+

Phone sensors are noisy and device-dependent. Our Hardware Abstraction Layer runs calibration:

-

After HAL, accelerometer output = net motion above road vibration, audio = net cabin noise above ambient. Device-agnostic.

-

Interpreting Audio Intensity

-

Audio features are acoustic aggregates only — no raw audio stored (privacy by design). Key features per 30s window:

- -

The insight: arguments have irregular cadence + sustained loudness, while music has regular cadence + steady levels. These two features alone separate ARGUMENT from MUSIC_OR_CALL well.

- -

Multi-Sensor Fusion

-

Dangerous situations are rarely single-sensor. The key fusion features:

- +

Data Privacy

+

Audio features are acoustic statistical aggregates only — no raw voice audio stored or transmitted to the backend (privacy by design). The backend parses numeric severity parameters alone.

-

Reducing False Positives

-
    -
  1. Platt calibration: Sigmoid recalibration so 85% confidence ≈ 85% true probability. Alerts only on HIGH (≥75%).
  2. -
  3. Confidence gating: If top-class confidence <50%, system defaults to NORMAL — no alert.
  4. -
  5. Class weighting: CONFLICT and ESCALATING weighted 3× during training (favour recall on dangerous events); Platt step corrects the resulting overconfidence.
  6. -
  7. Rule-based fallback: If model files are missing, simple thresholds (motion >3.5g + audio >80 dB → CONFLICT) ensure the app never crashes.
  8. -
- -

Output

-

Per 30s window: situation class (7 classes), calibrated confidence (HIGH / MEDIUM / LOW), top feature deviations (for explainability), safety flag, <1ms inference on CPU.

+

Output & Explainability

+

Engine spits out confidence intervals. When events occur, feature weights are analyzed to determine the exact cause (e.g. "You were braking too heavily") which drives the AI Safety Copilot.

- +
-

03 Earnings Velocity Algorithm

-

Current speed, forecasting, and cold-start handling.

- -

Pipeline

-
-
Driver Statetrips, hours, ₹
-
Feature Eng14 features
-
RF Regress300 trees
-
₹/hr + Status+ probability
-
- -

Current Earnings Speed

-

Earnings velocity = cumulative earnings ÷ elapsed hours (₹/hr). Required velocity = remaining earnings ÷ remaining hours. The gap between the two gives an instant "am I on track?" signal.

- -

Feature Engineering (14 features)

-
- - - - - -
GroupFeaturesWhy
Currentcurrent_velocity, elapsed_hours, trips_completed, trip_rateHow is the driver doing right now?
Contexthour_of_day, is_morning/lunch/evening_rushDemand varies by time of day
Historyvelocity_last_1/2/3, rolling_velocity_3/5Recent trend (momentum)
Goalgoal_pressure (target − current velocity)How urgently driver needs to speed up
- -

Forecasting

-

RF regressor predicts next-period velocity. From that we derive:

- - -

Handling Cold Start

-

First 15 min of a shift — no velocity lags, unstable trip rate, no rolling averages.

- - -
- Edge case: A driver with a ₹5,000 target and 2 hours left sees required = ₹2,500/hr — clearly unreachable. - The model predicts honestly; the dashboard shows 🔴 at_risk. We don't hide bad news. -
+

04 Driver Safety Goals Forecaster

+

Forecasting event tracking and goal resolution.

+ +

Users establish custom performance goals directly targeting weak habits identified by the AI. Trend line analysis determines if the driver is successfully migrating their driving habits towards the stated objective (e.g. fewer deep acceleration events). The ML trends calculate rolling regression to map success probability.

- +
-

04 Execution Strategy

-

MVP scope, phased build, and the cut line.

- -

MVP Scope

-
- - - - - - -
LayerWhat's included
ML — StressLightweight RF classifier, ~12 key features, 7 classes, Platt calibration, HAL, rule-based fallback
ML — EarningsRF regressor, 14 features, velocity prediction, 5 derived goal metrics
BackendFastAPI (25 endpoints), in-memory store, batch processor, CSV import, auth
FrontendReact SPA (8 pages, 16 components), maps, charts, explainability modals
Judge toolsPredict page (single-row testing), Batch Upload (CSV inference + charts)
- -

Phased Build

-
    -
  1. Data & Models — Feature engineering, train both RF models, validate with cross-validation.
  2. -
  3. Backend API — FastAPI with core endpoints, in-memory data store, batch inference.
  4. -
  5. Frontend Core — Dashboard, Trips, Trip Detail with map + charts, auth flow.
  6. -
  7. Polish & Judge Tools — Predict, Batch Upload, explainability, Trends, Goals.
  8. -
  9. Docs & Deploy — Design doc, architecture diagram, README, deployment.
  10. -
+

05 Execution Strategy

+

MVP scope and development milestones.

-

The Cut Line

+

Tech Stack Core

-

What we cut:

+

Frontend (Local Web/App)

    -
  • Real-time phone sensor streaming (simulated with synthetic data)
  • -
  • Persistent database (in-memory = zero-setup for judges)
  • -
  • Push notifications / WebSockets
  • -
  • Model retraining from feedback
  • -
  • Payment integration / real fare calculation
  • +
  • React 18 & Vite
  • +
  • Tailwind CSS (Glassmorphic implementation)
  • +
  • Recharts (Dashboard components)
  • +
  • Leaflet API (Risk Mapping)
-

Why:

+

Backend (Cloud Sync API)

    -
  • Each adds setup complexity without demonstrating core algorithm thinking
  • -
  • Architecture supports a DB — we just don't require one to run
  • -
  • Feedback collection is built; retraining is a production concern
  • -
  • Time focused on model quality + explainability + UX
  • +
  • Python 3.11 & FastAPI
  • +
  • Gemini LLM Toolkit
  • +
  • Random Forest Inference CLI
  • +
  • Batch processing hooks
- -

Key Trade-offs

-
- - - - -
ChoiceGainedGave Up
RandomForest over deep learningLightweight, interpretable, CPU-only, <1ms inferencePotentially lower accuracy on complex patterns
In-memory store over DBZero setup, instant startupNo persistence across restarts
Synthetic sensor dataFull control over class balanceMay not generalise to real sensors
-
- - -
-

05 Risk Maps & Spatial UX

-

How we show stress and “risk along route” without changing the trips list flow.

- -

Trip Detail — Risk along route

-

- The TripMap component (Leaflet + OSM tiles) receives the trip route, events (with offset_sec, severity, location, explain.summary), and total duration in seconds. - The polyline is split into segments at event indices derived from time along the route: calm stretches use a lighter blue; segments ending at an event use low / medium / high colours (green, amber, red) and slightly thicker strokes for higher severity. - Event markers use larger, ring-styled dots for high severity. Popups escape user-facing text and show label, severity, confidence, and a short explainability line when present. A small corner legend decodes colours and the playback cursor. -

- -

Predict — Demo high-risk zones

-

- RiskZonesPreviewMap shows a separate, static map centered on Bangalore with a few semi-transparent circles and popups labelled as demo / illustrative only — not live traffic or official crash data. - This previews a future “warn before entering risky segments” story without implying false precision. -

- -
- Scope: The trips list page is unchanged; map work is isolated to Trip Detail and Predict. -
- -
-

06 Judge Experience & Docker

-

How we designed the repo and Docker setup so judges can run DrivePulse in a few minutes.

- -

Zero-setup runtime

-

To avoid asking judges to install Python, Node, or ML libraries locally, we ship a fully containerised stack:

- + +
+

06 Deployment & Docker Setup

+

Zero-setup runtime orchestration.

-

Judge run instructions

-

We repeat the exact steps (as required by the hackathon) in the root README.md and docs:

+

The entire platform operates via containerised stacks to run concurrently without complex dependency resolution.

+
    -
  1. Install Docker Desktop and ensure it is running.
  2. -
  3. git clone ... && cd Driver-Pulse
  4. -
  5. From the repo root run: docker compose up --build
  6. -
  7. Visit http://localhost:5173 to use the app; optional backend health at http://localhost:8000/api/health.
  8. +
  9. Install Docker Desktop.
  10. +
  11. git clone the repository.
  12. +
  13. From root run: docker compose up --build
  14. +
  15. Navigate to http://localhost:5173 to explore the live DriverIntel dashboard.
-
- Judge login: we provide a pre-configured demo account so judges land in a realistic dashboard immediately.
- Username: judge@uber.com · Password: hackathon2026. -
- -
- This approach satisfies the hackathon's Docker criterion: a working Dockerfile and docker-compose.yml - at the repo root, with a single docker compose up --build command to start the entire application. -
- + diff --git a/driveintel_stress_model/requirements.txt b/driveintel_stress_model/requirements.txt index 1bedc27..2a9510f 100644 --- a/driveintel_stress_model/requirements.txt +++ b/driveintel_stress_model/requirements.txt @@ -2,3 +2,8 @@ pandas>=2.0.0 numpy>=1.24.0 scikit-learn>=1.3.0 joblib>=1.3.0 +fastapi==0.104.1 +uvicorn==0.24.0 +python-multipart==0.0.6 +pydantic==2.5.0 +pydantic-settings==2.1.0 \ No newline at end of file diff --git a/frontend/.env.production b/frontend/.env.production new file mode 100644 index 0000000..c5c3f48 --- /dev/null +++ b/frontend/.env.production @@ -0,0 +1 @@ +VITE_API_URL=https://your-vercel-deployment.vercel.app \ No newline at end of file diff --git a/frontend/index.html b/frontend/index.html index 578b394..f03963d 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -10,8 +10,11 @@ integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" /> + + + - +
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 9d95a17..5dbf2bc 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -70,7 +70,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1464,7 +1463,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -2048,7 +2046,6 @@ "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", "dev": true, "license": "MIT", - "peer": true, "bin": { "jiti": "bin/jiti.js" } @@ -2089,8 +2086,7 @@ "version": "1.9.4", "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz", "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==", - "license": "BSD-2-Clause", - "peer": true + "license": "BSD-2-Clause" }, "node_modules/lilconfig": { "version": "3.1.3", @@ -2314,7 +2310,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -2501,7 +2496,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -2514,7 +2508,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -2945,7 +2938,6 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -3039,7 +3031,6 @@ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", diff --git a/frontend/src/components/AICopilot.jsx b/frontend/src/components/AICopilot.jsx index 885015e..1c7529d 100644 --- a/frontend/src/components/AICopilot.jsx +++ b/frontend/src/components/AICopilot.jsx @@ -78,25 +78,29 @@ const AICopilot = () => { return (
{isOpen && ( -
-
-
-
-

DriveIntel Safety Assistant

+
+
+
+
+
+
+

Safety Copilot

+

Online & analyzing

+
-
-
+
{messages.map((m, i) => (
{/* USE THE NEW HELPER HERE */} @@ -104,17 +108,17 @@ const AICopilot = () => {
))} {isLoading && ( -
+
- Co-pilot is calculating... + Copilot is typing...
)}
-
+
setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && sendMessage()} @@ -122,7 +126,7 @@ const AICopilot = () => { @@ -132,9 +136,9 @@ const AICopilot = () => {
); diff --git a/frontend/src/components/ConfidenceBadge.jsx b/frontend/src/components/ConfidenceBadge.jsx index 9fe323c..5b4b8cd 100644 --- a/frontend/src/components/ConfidenceBadge.jsx +++ b/frontend/src/components/ConfidenceBadge.jsx @@ -1,15 +1,15 @@ const levelConfig = { - low: { bg: 'bg-green-100', text: 'text-green-800', label: 'Low' }, - medium: { bg: 'bg-yellow-100', text: 'text-yellow-800', label: 'Med' }, - high: { bg: 'bg-red-100', text: 'text-red-800', label: 'High' }, + low: { bg: 'bg-emerald-500/10 border-emerald-500/20', text: 'text-emerald-400', label: 'Low' }, + medium: { bg: 'bg-amber-500/10 border-amber-500/20', text: 'text-amber-400', label: 'Med' }, + high: { bg: 'bg-rose-500/10 border-rose-500/20', text: 'text-rose-400', label: 'High' }, } export default function ConfidenceBadge({ level, score }) { const cfg = levelConfig[level] || levelConfig.low return ( - + {cfg.label} - {score !== undefined && {Math.round(score * 100)}%} + {score !== undefined && {Math.round(score * 100)}%} ) } diff --git a/frontend/src/components/EventCard.jsx b/frontend/src/components/EventCard.jsx index be8cab2..ad07136 100644 --- a/frontend/src/components/EventCard.jsx +++ b/frontend/src/components/EventCard.jsx @@ -8,10 +8,10 @@ export default function EventCard({ event, onJumpTo, onFeedback }) { const [showExplain, setShowExplain] = useState(false) const severityColor = { - low: 'border-l-uber-green', - medium: 'border-l-uber-yellow', - high: 'border-l-uber-red', - }[event.severity] || 'border-l-uber-gray-300' + low: 'border-l-emerald-500 shadow-[0_4px_20px_rgba(16,185,129,0.1)]', + medium: 'border-l-amber-500 shadow-[0_4px_20px_rgba(245,158,11,0.1)]', + high: 'border-l-rose-500 shadow-[0_4px_20px_rgba(244,63,94,0.15)]', + }[event.severity] || 'border-l-slate-700' const time = event.timestamp ? new Date(event.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }) @@ -19,24 +19,25 @@ export default function EventCard({ event, onJumpTo, onFeedback }) { return ( <> -
-
+
+
+
- {event.emoji} - {event.label.replace(/_/g, ' ')} + {event.emoji} + {event.label.replace(/_/g, ' ')}
-

{time}

+

{time}

{event.explain?.summary && ( -

{event.explain.summary}

+

{event.explain.summary}

)}
-
+
-
+
e.stopPropagation()} > {/* Header */} -
+
-

Why This Happened

-

- {event.emoji} {event.label.replace(/_/g, ' ')} +

Why This Happened

+

+ {event.emoji} {event.label.replace(/_/g, ' ')}

-
{/* Top 3 feature contributions */} -
-

Top Feature Contributions

+
+

Top Feature Contributions

{explain.top_features?.map((f, i) => { const pct = Math.round(f.contribution * 100) - const barColor = i === 0 ? 'bg-uber-red' : i === 1 ? 'bg-uber-orange' : 'bg-uber-yellow' + const barColor = i === 0 ? 'bg-rose-500 shadow-[0_0_8px_rgba(244,63,94,0.6)]' : i === 1 ? 'bg-amber-500 shadow-[0_0_8px_rgba(245,158,11,0.6)]' : 'bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.6)]' return (
-
- - {f.feature.replace(/_/g, ' ')} {f.direction} +
+ + {f.feature.replace(/_/g, ' ')} {f.direction} - {pct}% + {pct}%
-
+
@@ -48,14 +48,14 @@ export default function ExplainModal({ event, onClose }) {
{/* Model inputs */} -
-

Model Inputs (snapshot)

-
+
+

Model Inputs (snapshot)

+
{explain.model_inputs && Object.entries(explain.model_inputs).map(([k, v]) => ( -
- {k.replace(/_/g, ' ')} - {v} +
+ {k.replace(/_/g, ' ')} + {v}
))}
@@ -63,8 +63,8 @@ export default function ExplainModal({ event, onClose }) { {/* Summary */} {explain.summary && ( -
-

{explain.summary}

+
+

"{explain.summary}"

)}
diff --git a/frontend/src/components/FeedbackButtons.jsx b/frontend/src/components/FeedbackButtons.jsx index d705f50..b614bcf 100644 --- a/frontend/src/components/FeedbackButtons.jsx +++ b/frontend/src/components/FeedbackButtons.jsx @@ -5,7 +5,7 @@ import { api } from '../api/client' const options = [ { key: 'correct', label: 'Correct', icon: ThumbsUp, color: 'text-uber-green hover:bg-green-50' }, { key: 'incorrect', label: 'Incorrect', icon: ThumbsDown, color: 'text-uber-red hover:bg-red-50' }, - { key: 'not_relevant', label: 'Not Relevant', icon: MinusCircle, color: 'text-uber-gray-500 hover:bg-uber-gray-100' }, + { key: 'not_relevant', label: 'Not Relevant', icon: MinusCircle, color: 'text-slate-500 hover:bg-slate-800' }, ] export default function FeedbackButtons({ eventId, current, onFeedback }) { @@ -28,7 +28,7 @@ export default function FeedbackButtons({ eventId, current, onFeedback }) { return (
- Feedback: + Feedback: {options.map(({ key, label, icon: Icon, color }) => ( +
+
+
+

Quick Start

+

Explore a Sample Trip

+

+ See stress detection, earnings tracking, and event explainability in action. +

+ +
) } diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx index 3b2b5f5..cd0336a 100644 --- a/frontend/src/components/Sidebar.jsx +++ b/frontend/src/components/Sidebar.jsx @@ -12,36 +12,36 @@ const links = [ export default function Sidebar({ user, onLogout }) { return ( -