walgar/ckd
1
1from fastapi import FastAPI, HTTPException2from pydantic import BaseModel3import joblib4import os5import pandas as pd6 7# ✅ Load the model with correct path8MODEL_PATH = os.path.join(os.path.dirname(__file__), "random_forest_model_compatible.pkl")9 10try:11 model = joblib.load(MODEL_PATH)12 print("✅ Model loaded successfully.")13except Exception as e:14 print(f"❌ Failed to load model: {e}")15 raise16 17# ✅ Define FastAPI app18app = FastAPI(title="CKD Prediction API")19 20# ✅ Input schema (must match the model's features)21class CKDInput(BaseModel):22 age: float23 blood_pressure: float24 specific_gravity: float25 albumin: float26 sugar: float27 red_blood_cells: int28 pus_cell: int29 pus_cell_clumps: int30 bacteria: int31 blood_glucose_random: float32 blood_urea: float33 serum_creatinine: float34 sodium: float35 potassium: float36 haemoglobin: float37 packed_cell_volume: float38 white_blood_cell_count: float39 red_blood_cell_count: float40 hypertension: int41 diabetes_mellitus: int42 coronary_artery_disease: int43 appetite: int44 peda_edema: int45 aanemia: int46 47# ✅ Prediction endpoint48@app.post("/predict")49async def predict_ckd(data: CKDInput):50 try:51 # Convert to DataFrame52 input_df = pd.DataFrame([data.dict()])53 54 # Predict55 prediction = model.predict(input_df)[0]56 57 # Interpret result58 result = "ckd" if prediction == 1 else "nockd"59 60 return {"prediction": result}61 62 except Exception as e:63 raise HTTPException(status_code=500, detail=f"Prediction error: {e}")64 65# Root endpoint (optional)66@app.get("/")67def read_root():68 return {"message": "Welcome to CKD Prediction API!"}69 