Spaces:
Runtime error
Runtime error
Download app/api/routes.py from devmurtaza/RastaAI: direct link, hf CLI and curl.
- Browser
- Download file 4.12 kB
-
https://huggingface.co/spaces/devmurtaza/RastaAI/resolve/main/app/api/routes.py
- Command line
-
hf download hf://spaces/devmurtaza/RastaAI/app/api/routes.py
-
curl -L -o routes.py https://huggingface.co/spaces/devmurtaza/RastaAI/resolve/main/app/api/routes.py
4.12 kB
| """Route prediction + reroute endpoints.""" | |
| from __future__ import annotations | |
| from datetime import datetime | |
| from typing import List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, Query | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, desc | |
| from app.database import get_db | |
| from app.models.db_models import RoutePrediction | |
| from app.schemas.route import ( | |
| PredictRouteRequest, PredictRouteResponse, | |
| RerouteRequest, LocationInput, Coordinate, | |
| RouteHistoryItem, | |
| ) | |
| from app.services.predict_service import predict_route | |
| from app.utils.logger import logger | |
| router = APIRouter(tags=["routes"]) | |
| async def predict_route_endpoint( | |
| req: PredictRouteRequest, | |
| db: AsyncSession = Depends(get_db), | |
| ) -> PredictRouteResponse: | |
| try: | |
| response = await predict_route(req) | |
| except ValueError as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| except Exception as e: | |
| logger.exception("predict_route failed") | |
| raise HTTPException(status_code=500, detail=f"Prediction failed: {e}") | |
| # Persist | |
| try: | |
| origin_coord = req.origin.coordinate | |
| dest_coord = req.destination.coordinate | |
| best = response.ranked_routes[0] | |
| # Resolve fallback coordinates from the polyline if user passed only an id | |
| ox, oy = best.polyline[0].lat, best.polyline[0].lng | |
| dx, dy = best.polyline[-1].lat, best.polyline[-1].lng | |
| record = RoutePrediction( | |
| user_id=req.user_id, | |
| origin_lat=(origin_coord.lat if origin_coord else ox), | |
| origin_lng=(origin_coord.lng if origin_coord else oy), | |
| origin_name=req.origin.name or req.origin.id, | |
| destination_lat=(dest_coord.lat if dest_coord else dx), | |
| destination_lng=(dest_coord.lng if dest_coord else dy), | |
| destination_name=req.destination.name or req.destination.id, | |
| vehicle_type=req.vehicle_type, | |
| preference=req.preference, | |
| chosen_route_id=best.route_id, | |
| eta_predicted_min=best.eta_minutes, | |
| fuel_predicted_l=best.fuel_liters, | |
| distance_km=best.distance_km, | |
| ranked_payload=response.model_dump(mode="json"), | |
| ) | |
| db.add(record) | |
| except Exception as e: | |
| logger.warning(f"Failed to persist prediction: {e}") | |
| return response | |
| async def reroute(req: RerouteRequest) -> PredictRouteResponse: | |
| """Re-plan from current position to the original destination.""" | |
| predict_req = PredictRouteRequest( | |
| origin=LocationInput( | |
| coordinate=Coordinate(lat=req.current_position.lat, lng=req.current_position.lng), | |
| name="Current position", | |
| ), | |
| destination=LocationInput( | |
| coordinate=Coordinate(lat=req.remaining_destination.lat, lng=req.remaining_destination.lng), | |
| ), | |
| departure_time=datetime.utcnow(), | |
| vehicle_type=req.vehicle_type, | |
| preference=req.preference, | |
| user_id=req.user_id, | |
| ) | |
| response = await predict_route(predict_req) | |
| response.reroute_suggested = True | |
| return response | |
| async def history( | |
| user_id: Optional[str] = Query(None), | |
| limit: int = Query(20, ge=1, le=100), | |
| db: AsyncSession = Depends(get_db), | |
| ) -> List[RouteHistoryItem]: | |
| stmt = select(RoutePrediction).order_by(desc(RoutePrediction.created_at)).limit(limit) | |
| if user_id: | |
| stmt = stmt.where(RoutePrediction.user_id == user_id) | |
| rows = (await db.execute(stmt)).scalars().all() | |
| return [ | |
| RouteHistoryItem( | |
| id=r.id, | |
| user_id=r.user_id, | |
| origin_name=r.origin_name, | |
| destination_name=r.destination_name, | |
| chosen_route_id=r.chosen_route_id, | |
| eta_predicted_min=r.eta_predicted_min, | |
| eta_actual_min=r.eta_actual_min, | |
| created_at=r.created_at, | |
| ) | |
| for r in rows | |
| ] | |