Spaces:
Sleeping
Sleeping
Download app/main.py from FransiMengesha/rta-api: direct link, hf CLI and curl.
- Browser
- Download file 8.09 kB
-
https://huggingface.co/spaces/FransiMengesha/rta-api/resolve/main/app/main.py
- Command line
-
hf download hf://spaces/FransiMengesha/rta-api/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/FransiMengesha/rta-api/resolve/main/app/main.py
8.09 kB
| """ | |
| Ethiopian Road Traffic Accident Severity Prediction | |
| FastAPI Backend | |
| """ | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, Field | |
| from typing import Optional | |
| import pandas as pd | |
| import joblib | |
| import json | |
| import os | |
| # ββ App Setup ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app = FastAPI( | |
| title="Ethiopian RTA Severity Prediction API", | |
| description="Predicts road accident severity (Slight / Serious / Fatal) using XGBoost with L1+L2 regularization. Trained on Addis Ababa Police Department records.", | |
| version="1.0.0", | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # ββ Load Model βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| MODEL_PATH = os.path.join(BASE_DIR, '..', 'models', 'best_rta_model.pkl') | |
| METADATA_PATH = os.path.join(BASE_DIR, '..', 'models', 'model_metadata.json') | |
| model = joblib.load(MODEL_PATH) | |
| with open(METADATA_PATH) as f: | |
| metadata = json.load(f) | |
| CLASS_NAMES = metadata['classes'] | |
| # ββ Request Schema βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class AccidentInput(BaseModel): | |
| Time: str = Field(..., example="Night (22-6)") | |
| Day_of_week: str = Field(..., example="Friday") | |
| Age_band_of_driver: str = Field(..., example="18-30") | |
| Sex_of_driver: str = Field(..., example="Male") | |
| Educational_level: str = Field(..., example="High school") | |
| Vehicle_driver_relation: str = Field(..., example="Employee") | |
| Driving_experience: str = Field(..., example="Below 1yr") | |
| Lanes_or_Medians: str = Field(..., example="Undivided Two way") | |
| Types_of_Junction: str = Field(..., example="Y Shape") | |
| Road_surface_type: str = Field(..., example="Asphalt roads") | |
| Road_surface_conditions: str = Field(..., example="Wet or damp") | |
| Light_conditions: str = Field(..., example="Darkness - no lighting") | |
| Weather_conditions: str = Field(..., example="Raining") | |
| Type_of_collision: str = Field(..., example="Rollover") | |
| Number_of_vehicles_involved: int = Field(..., ge=1, le=10, example=3) | |
| Number_of_casualties: int = Field(..., ge=1, le=20, example=4) | |
| Vehicle_type: str = Field(..., example="Lorry (41-100Q)") | |
| Cause_of_accident: str = Field(..., example="Drunk driving") | |
| Pedestrian_movement: str = Field(..., example="Crossing from nearside") | |
| Vehicle_movement: str = Field(..., example="Going straight") | |
| Type_of_vehicle: str = Field(..., example="Long lorry") | |
| Road_allignment: str = Field(..., example="Tangent road with flat terrain") | |
| Area_accident_occured: str = Field(..., example="Residential areas") | |
| Sub_district: str = Field(..., example="Bole") | |
| # ββ Response Schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class PredictionResponse(BaseModel): | |
| predicted_severity: str | |
| severity_code: int | |
| confidence: float | |
| confidence_pct: str | |
| probabilities: dict | |
| risk_level: str | |
| model_name: str | |
| model_accuracy: float | |
| class HealthResponse(BaseModel): | |
| status: str | |
| model: str | |
| accuracy: float | |
| f1_weighted: float | |
| roc_auc: float | |
| dataset: str | |
| records: int | |
| # ββ Routes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def root(): | |
| return { | |
| "service": "Ethiopian RTA Severity Prediction API", | |
| "version": "1.0.0", | |
| "endpoints": { | |
| "POST /predict": "Predict accident severity", | |
| "GET /health": "Model health and performance stats", | |
| "GET /classes": "Available target classes", | |
| "GET /features": "Available feature values", | |
| "GET /docs": "Swagger UI", | |
| } | |
| } | |
| def health(): | |
| return HealthResponse( | |
| status="healthy", | |
| model=metadata["model_name"], | |
| accuracy=metadata["test_accuracy"], | |
| f1_weighted=metadata["test_f1_weighted"], | |
| roc_auc=metadata["test_roc_auc"], | |
| dataset="Mendeley 2017-2020 + Figshare 2016-2022", | |
| records=25380, | |
| ) | |
| def get_classes(): | |
| return { | |
| "classes": { | |
| 0: "Slight Injury", | |
| 1: "Serious Injury", | |
| 2: "Fatal injury", | |
| }, | |
| "distribution": { | |
| "Slight Injury": "78.8%", | |
| "Serious Injury": "20.1%", | |
| "Fatal injury": "1.1%", | |
| } | |
| } | |
| def get_features(): | |
| return { | |
| "categorical_features": metadata.get("cat_unique", {}), | |
| "numerical_features": { | |
| "Number_of_vehicles_involved": {"type": "int", "min": 1, "max": 5}, | |
| "Number_of_casualties": {"type": "int", "min": 1, "max": 8}, | |
| } | |
| } | |
| def predict(data: AccidentInput): | |
| try: | |
| input_dict = data.model_dump() | |
| input_df = pd.DataFrame([input_dict]) | |
| pred_class = int(model.predict(input_df)[0]) | |
| pred_proba = model.predict_proba(input_df)[0] | |
| confidence = float(pred_proba[pred_class]) | |
| pred_label = CLASS_NAMES[pred_class] | |
| risk_map = { | |
| "Slight Injury": "LOW", | |
| "Serious Injury": "MEDIUM", | |
| "Fatal injury": "HIGH", | |
| } | |
| return PredictionResponse( | |
| predicted_severity = pred_label, | |
| severity_code = pred_class, | |
| confidence = round(confidence, 4), | |
| confidence_pct = f"{confidence*100:.1f}%", | |
| probabilities = { | |
| CLASS_NAMES[i]: round(float(p), 4) | |
| for i, p in enumerate(pred_proba) | |
| }, | |
| risk_level = risk_map[pred_label], | |
| model_name = metadata["model_name"], | |
| model_accuracy = metadata["test_accuracy"], | |
| ) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| def predict_batch(data: list[AccidentInput]): | |
| if len(data) > 100: | |
| raise HTTPException(status_code=400, detail="Batch limit is 100 records.") | |
| results = [] | |
| for item in data: | |
| try: | |
| input_df = pd.DataFrame([item.model_dump()]) | |
| pred_class = int(model.predict(input_df)[0]) | |
| pred_proba = model.predict_proba(input_df)[0] | |
| results.append({ | |
| "predicted_severity": CLASS_NAMES[pred_class], | |
| "confidence": round(float(pred_proba[pred_class]), 4), | |
| "probabilities": {CLASS_NAMES[i]: round(float(p), 4) | |
| for i, p in enumerate(pred_proba)}, | |
| }) | |
| except Exception as e: | |
| results.append({"error": str(e)}) | |
| return {"predictions": results, "total": len(results)} | |
| # ββ Run ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) | |