Spaces:
Runtime error
Runtime error
File size: 12,518 Bytes
1bc8a37 0ddcb86 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | ---
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<Route[]> {
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.
|