--- title: RastaAI emoji: ๐Ÿš— colorFrom: green colorTo: blue sdk: docker app_port: 8000 pinned: false --- # RastaAI Backend โ€” Route Intelligence Engine AI-powered route ranking and ETA prediction for Pakistan. Companion backend to the RastaAI Expo/React Native app. **Stack:** Python 3.11 ยท FastAPI ยท PostgreSQL ยท Redis ยท XGBoost / LightGBM ยท OSRM ยท Docker > *Not a Google Maps wrapper. A route intelligence engine that learns from traffic, weather, time-of-day, vehicle, and user feedback to predict the best route per trip.* --- ## What this backend does For any (origin, destination, vehicle, preference) request, it: 1. Generates **3 candidate routes** via OSRM (free, open-source) with a synthetic-Bezier fallback for offline dev. 2. Extracts a **13-dimensional feature vector** per route (distance, turns, road type, traffic, weather, time-of-day, vehicle, etc.). 3. Predicts **ETA** and **fuel consumption** with a trained XGBoost / LightGBM regressor (auto-falls-back to a physics estimator if no model is loaded). 4. Computes **traffic risk**, **reliability**, and **confidence** scores. 5. **Ranks** all routes with configurable preference-weighted scoring (`fastest`, `fuel_saving`, `balanced`, `safer_route`). 6. Returns ranked routes with a **human-readable explanation** of why the best one won. 7. Caches by (origin, destination, hour-of-day, vehicle, preference) in Redis for ~5 min. 8. Persists every prediction in Postgres so feedback can drive future retraining. --- ## Quick start ### Option A โ€” Docker (recommended) ```bash cp .env.example .env docker compose up --build ``` API at `http://localhost:8000`. Swagger UI at `http://localhost:8000/docs`. The Dockerfile pre-trains a baseline model during the build, so `/predict-route` works on the first request. ### Option B โ€” local Python ```bash python -m venv .venv && source .venv/bin/activate pip install -r requirements.txt cp .env.example .env # Spin up DB + Redis somewhere (e.g. docker compose up db redis) # Then train a baseline model (one-time): python -m app.training.train # Run the API uvicorn app.main:app --reload --port 8000 ``` --- ## Folder structure ``` app/ main.py โ† FastAPI entry, router wiring, lifespan config.py โ† pydantic-settings env loader database.py โ† SQLAlchemy async engine + session api/ health.py โ† GET /health routes.py โ† POST /predict-route, /reroute, GET /routes/history training.py โ† POST /train-model, GET /model/status feedback.py โ† POST /feedback cities.py โ† GET /cities models/ db_models.py โ† SQLAlchemy ORM tables inference.py โ† Loaded XGB/LGBM bundle + physics fallback ranker.py โ† Preference-weighted scoring artifacts/ โ† Saved joblib models (.gitignored) services/ locations.py โ† Pakistani city catalog route_provider.py โ† OSRM + Bezier fallback feature_extractor.py โ† Builds the ML feature vector traffic_service.py โ† Deterministic traffic heuristic weather_service.py โ† OpenWeather API client cache_service.py โ† Async Redis wrapper explanation.py โ† Strengths/tradeoffs + final rationale predict_service.py โ† THE ORCHESTRATOR schemas/ route.py โ† All Pydantic request/response models training/ synthetic_data.py โ† Physics-informed dataset generator preprocess.py โ† ColumnTransformer (scaler + one-hot) train.py โ† End-to-end training pipeline jobs/ retrain.py โ† Scheduled retraining entry point utils/ geometry.py โ† Haversine, turns, bbox logger.py โ† Loguru tests/ test_smoke.py โ† Async httpx integration tests Dockerfile docker-compose.yml requirements.txt .env.example ``` --- ## API reference Base path: `/api/v1`. Full spec at `/docs`. ### `GET /health` Liveness + DB + Redis check. ### `POST /predict-route` โญ Main endpoint. ```json { "origin": { "id": "karachi" }, "destination": { "id": "lahore" }, "vehicle_type": "car", "preference": "balanced", "departure_time": "2026-05-30T17:00:00Z", "user_id": "uid_123" } ``` You can pass raw coordinates instead of an id: ```json { "origin": { "coordinate": { "lat": 24.86, "lng": 67.00 }, "name": "Home" }, ... } ``` **Response (abridged):** ```json { "best_route_id": "9b1a-โ€ฆ", "explanation": "Picked because you asked to optimise for an overall balance...", "ranked_routes": [ { "route_id": "9b1a-โ€ฆ", "label": "Smart", "polyline": [{"lat": 24.86, "lng": 67.00}, ...], "eta_minutes": 1142.3, "eta_arrival": "2026-05-31T12:02:00Z", "distance_km": 1218.4, "fuel_liters": 98.7, "fuel_cost_pkr": 27636, "traffic_risk": 0.42, "reliability": 0.81, "confidence": 0.84, "score": 0.7321, "is_best": true, "strengths": ["High confidence (84%)", "Best road quality"], "tradeoffs": ["~12 min slower than the express option"], "features": { "road_type": "motorway", "traffic_level": 0.42, ... }, "turns": [ ... ] } ], "generated_at": "2026-05-30T17:00:01Z", "cached": false } ``` ### `POST /reroute` Replan from current GPS position to the destination. Returns the same shape as `/predict-route` with `reroute_suggested: true`. ```json { "current_route_id": "9b1a-โ€ฆ", "current_position": { "lat": 28.4, "lng": 70.3 }, "remaining_destination": { "lat": 31.52, "lng": 74.36 }, "vehicle_type": "car", "preference": "fastest" } ``` ### `POST /train-model` Run a full training pass. Returns metrics and reloads the in-memory model. ```json { "synthetic_samples": 20000, "test_size": 0.2, "model_type": "xgboost" } ``` ### `GET /model/status` Whether models are loaded, paths, last-trained timestamp. ### `POST /feedback` Record real-world results for a finished trip; updates the linked prediction row. ```json { "route_id": "9b1a-โ€ฆ", "actual_eta_minutes": 1198, "actual_fuel_liters": 102.0, "rating": 4, "completed": true } ``` ### `GET /routes/history?user_id=โ€ฆ&limit=20` Prediction history for a user. ### `GET /cities?q=โ€ฆ` Pakistani city search (mirrors the frontend `locationService`). --- ## How the model works ### Features (per candidate route) | Numeric | Categorical | |---|---| | distance_km | road_type (motorway/highway/primary/urban/mixed) | | nominal_speed_kmh | vehicle_type (car/motorbike/truck/rickshaw) | | turns | | | turns_per_km | | | traffic_level (0โ€“1) | | | road_quality (0โ€“1) | | | hour_of_day (0โ€“23) | | | day_of_week (0โ€“6) | | | weather_severity (0โ€“1) | | | detour_ratio | | Preprocessing is a single `ColumnTransformer` (StandardScaler + OneHotEncoder) saved alongside the model so inference encodes identically to training. ### Targets - **ETA (minutes)** โ€” regression - **Fuel (litres)** โ€” regression Both trained on a physics-informed synthetic dataset (`app/training/synthetic_data.py`). The generator models realistic Pakistani driving conditions: rush-hour curves, vehicle-specific fuel envelopes with parabolic minima at optimum cruising speed, weather penalties, and road-type speed profiles. This lets the system serve real OSRM routes immediately without waiting for real-world data. ### Ranking Composite score per route: ``` score = w_eta * (1 - norm_eta) + w_traffic * (1 - traffic_level) + w_fuel * (1 - norm_fuel) + w_road * road_quality + w_pref * preference_match ``` Weights switch by `preference` mode: | Mode | ETA | Traffic | Fuel | Road | Pref | |---|---|---|---|---|---| | fastest | 0.65 | 0.20 | 0.05 | 0.05 | 0.05 | | fuel_saving | 0.15 | 0.15 | 0.55 | 0.10 | 0.05 | | balanced | 0.40 | 0.25 | 0.20 | 0.10 | 0.05 | | safer_route | 0.20 | 0.25 | 0.10 | 0.40 | 0.05 | Callers can also pass `weights` in the request to override. --- ## Wiring this to the existing Expo app Your frontend already has the right shape โ€” `useRouteStore.routes: Route[]` plus a `routeService.buildRoutes()` placeholder. Replace `buildRoutes()` with one network call: ```ts // src/services/routeService.ts import { useUserStore } from "@/store/useUserStore"; const API = process.env.EXPO_PUBLIC_API_URL ?? "http://10.0.2.2:8000/api/v1"; export async function buildRoutes( origin: City, destination: City, preferences: Preferences, ): Promise { const res = await fetch(`${API}/predict-route`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ origin: { id: origin.id }, destination: { id: destination.id }, vehicle_type: preferences.vehicle ?? "car", preference: preferences.mode ?? "balanced", user_id: useUserStore.getState().profile.id, }), }); if (!res.ok) throw new Error(`API ${res.status}`); const data = await res.json(); return data.ranked_routes.map((r: any) => ({ id: r.route_id, label: r.label, polyline: r.polyline, etaMinutes: r.eta_minutes, distanceKm: r.distance_km, fuelLiters: r.fuel_liters, fuelCost: r.fuel_cost_pkr, confidence: r.confidence, isBest: r.is_best, strengths: r.strengths, tradeoffs: r.tradeoffs, explanation: r.label === "Smart" ? data.explanation : "", })); } ``` Android emulator uses `10.0.2.2` to reach localhost. Physical device โ€” use your LAN IP. For feedback after a completed trip: ```ts await fetch(`${API}/feedback`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ route_id: activeRoute.id, actual_eta_minutes: elapsedMin, completed: true, rating: 5, }), }); ``` --- ## Running locally without Docker ```bash # 1. install pip install -r requirements.txt # 2. .env cp .env.example .env # Edit DATABASE_URL / REDIS_URL to point at your local instances, # or leave the defaults and run: docker compose up db redis # 3. baseline model python -m app.training.train # 4. run uvicorn app.main:app --reload ``` Then: ```bash curl http://localhost:8000/api/v1/health curl -X POST http://localhost:8000/api/v1/predict-route \ -H "Content-Type: application/json" \ -d '{"origin":{"id":"karachi"},"destination":{"id":"lahore"},"preference":"balanced"}' ``` --- ## Tests ```bash pip install pytest pytest-asyncio pytest -q ``` The smoke suite uses `httpx.ASGITransport` so it runs against the FastAPI app in-process โ€” no live DB or Redis needed. --- ## Production checklist - [ ] Replace OSRM public demo with self-hosted OSRM or Google Directions - [ ] Wire `weather_service.py` to a paid weather provider for SLA - [ ] Replace deterministic traffic heuristic with TomTom / HERE / INRIX - [ ] Hook fuel price to OGRA daily feed instead of static PKR 280/L - [ ] Run Alembic migrations instead of `Base.metadata.create_all` - [ ] Move `/train-model` onto a Celery / Arq worker - [ ] Add API auth (API keys per app build, or Firebase Auth tokens) - [ ] Add structured request logging + tracing (OpenTelemetry) - [ ] Periodic retrain via cron / k8s CronJob calling `app.jobs.retrain` - [ ] Persistent volume for `app/models/artifacts/` so trained models survive container restarts - [ ] Pin model version in responses for reproducibility - [ ] Add unit tests for `ranker.py` and `feature_extractor.py` --- ## What's still synthetic (honest gap) The frontend build log called out 8% of the product. The backend now closes most of the model-side gaps: | Was synthetic | Status | |---|---| | Routes as Bezier curves | โœ… Real OSRM routes (fallback only when OSRM down) | | ETA = distance / 85 | โœ… Trained XGB/LGBM regressor on physics-informed dataset | | Fuel = static 280 PKR/L | โš ๏ธ Still static; multiply happens server-side now (easy to plug in OGRA feed) | | Traffic = Math.random() | โš ๏ธ Now a deterministic time-of-day + DOW heuristic. Real provider TBD. | | No persistence | โœ… Postgres + per-prediction history | | No caching | โœ… Redis with TTL | | No learning loop | โœ… Feedback endpoint feeds future retraining | The architecture is genuinely production-shaped: every external dependency (routing, traffic, weather, fuel-price) is a single-file service you can swap without touching the orchestrator or the model.