Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, HTTPException, Query | |
| from weather_pipeline import WeatherPipeline | |
| from model import TrafficRiskModel | |
| import os | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv() | |
| app = FastAPI(title="Weather-Traffic Risk API") | |
| # Setup | |
| WEATHER_API_KEY = os.getenv("WEATHER_API_KEY", "your_api_key_here") | |
| weather_pipeline = WeatherPipeline(WEATHER_API_KEY) | |
| risk_model = TrafficRiskModel() | |
| async def root(): | |
| return { | |
| "message": "Welcome to the Weather-Traffic Risk Prediction API", | |
| "endpoints": { | |
| "/weather/{city}": "Get weather data and traffic risk prediction for a city" | |
| } | |
| } | |
| async def get_weather_risk( | |
| city: str, | |
| lat: float = Query(None, description="Optional latitude for high precision"), | |
| lon: float = Query(None, description="Optional longitude for high precision") | |
| ): | |
| # 1. Fetch and process weather data (Lat/Lon takes priority for precision) | |
| data = weather_pipeline.get_weather(city=city, lat=lat, lon=lon) | |
| if "error" in data: | |
| raise HTTPException(status_code=400, detail=data["error"]) | |
| # 2. Predict Traffic Risk using ML model | |
| risk_level, confidence = risk_model.predict( | |
| data["temp"], | |
| data["rain"], | |
| data["condition"] | |
| ) | |
| # 3. Combine results in the FINAL God-Level format | |
| result = { | |
| "city": city, | |
| "timestamp": data.get("timestamp"), | |
| "source": data.get("source"), | |
| "coordinates": {"lat": lat, "lon": lon} if lat and lon else "Default City Center", | |
| "weather": { | |
| "actual_temp": data["temp"], | |
| "feels_like": data["feels_like"], | |
| "rainfall_mm": data["rain"], | |
| "condition": data["condition"], | |
| "condition_raw": data["condition_raw"] | |
| }, | |
| "derived_weather_metrics": data["derived_metrics"], | |
| "ml_prediction": { | |
| "traffic_risk_level": risk_level, | |
| "confidence": round(float(confidence), 2), | |
| "status_color": get_risk_color(risk_level) | |
| } | |
| } | |
| return result | |
| def get_risk_color(risk_level): | |
| mapping = { | |
| "Low": "🟢 Green", | |
| "Medium": "🟡 Yellow", | |
| "High": "🔴 Red" | |
| } | |
| return mapping.get(risk_level, "⚪ Unknown") | |
| if __name__ == "__main__": | |
| import uvicorn | |
| # Train model on startup if needed | |
| if not risk_model.load(): | |
| print("Training model...") | |
| risk_model.train() | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |