CoolFace
Apppublic

bhavin273/demand-prediction-api

sourceHugging Facemitupdated 8mo agoView on Hugging Face
0likes
app.py91 linesDownload Raw Back to root
1from fastapi import FastAPI, HTTPException2from pydantic import BaseModel3from datetime import datetime4import pandas as pd5from train_model import predict_demand6import uvicorn7 8app = FastAPI(title="Dynamic Parking Demand Predictor API")9 10class PredictRequest(BaseModel):11    h3_cell: str12    timestamp: str13    14    class Config:15        json_schema_extra = {16            "example": {17                "h3_cell": "8c2a100d1a2bfff",18                "timestamp": "2026-01-19 14:00:00"19            }20        }21 22class PredictResponse(BaseModel):23    h3_cell: str24    timestamp: str25    demand_factor: float26 27class HealthResponse(BaseModel):28    status: str29 30@app.post('/predict', response_model=PredictResponse)31def predict(request: PredictRequest):32    """33    Predict demand factor for a given h3_cell and timestamp.34    35    Expected JSON payload:36    {37        "h3_cell": "string",38        "timestamp": "YYYY-MM-DD HH:MM:SS" or datetime string39    }40    41    Returns:42    {43        "h3_cell": "string",44        "timestamp": "string",45        "demand_factor": float46    }47    """48    try:49        # Convert timestamp to datetime50        timestamp = pd.to_datetime(request.timestamp).round('H')51        52        # Predict demand53        demand_factor = predict_demand(request.h3_cell, timestamp)54        55        if demand_factor is None:56            raise HTTPException(57                status_code=404,58                detail=f"No data found for h3_cell: {request.h3_cell} at timestamp: {request.timestamp}"59            )60        61        return PredictResponse(62            h3_cell=request.h3_cell,63            timestamp=str(timestamp),64            demand_factor=demand_factor65        )66        67    except HTTPException:68        raise69    except Exception as e:70        raise HTTPException(status_code=500, detail=str(e))71 72@app.get('/health', response_model=HealthResponse)73def health():74    """Health check endpoint"""75    return HealthResponse(status="healthy")76 77@app.get('/')78def root():79    """Root endpoint with API information"""80    return {81        "message": "Dynamic Parking Demand Predictor API",82        "endpoints": {83            "POST /predict": "Predict demand factor",84            "GET /health": "Health check",85            "GET /docs": "Interactive API documentation"86        }87    }88 89if __name__ == '__main__':90    uvicorn.run(app, host='0.0.0.0', port=7860)91