RastaAI / README.md
devmurtaza's picture
Fix HF Spaces port config (app_port: 8000) and set sdk: docker
1bc8a37
|
Raw History Blame Contribute Delete
12.5 kB
---
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.