import numpy as np from fastapi import FastAPI from pydantic import BaseModel import joblib import pickle app = FastAPI() def load_model(): try: model = joblib.load("model.joblib") print("Model Load Successfully") return model except Exception as e: print(f"Error loading model: {e}") model = None return model def load_scaler(): try: with open("scaler.pkl", 'rb') as file: scaler = pickle.load(file) print("Scaler loaded successfully") return scaler except: return ("Error while loading scaler") def load_encoder(): try: with open("encoder.pkl", 'rb') as file: encoder = pickle.load(file) print("Encoder loaded successfully") return encoder except: print("Error while loading encoder") model = load_model() encoder = load_encoder() scaler = load_scaler() def load_data(data): gender = 1 if data.Gender == 'Male' else 0 age = data.Age neighbourhood = encoder.transform([data.Neighbourhood])[0] scholarship = 1 if data.Scholarship == 'Yes' else 0 hipertension = 1 if data.Hipertension == 'Yes' else 0 diabetes = 1 if data.Diabetes == 'Yes' else 0 alcoholism = 1 if data.Alcoholism == 'Yes' else 0 handcap = 1 if data.Handcap == 'Yes' else 0 smsreceived = 1 if data.SMSreceived == "Yes" else 0 waitingtime = data.WaitingTime appointmentDayWeek = data.AppointmentDayOfWeek lst = ['SameDay', 'Short', 'Mid', 'Long', 'VeryLong'] waitingGroup = lst.index(data.WaitingGroup) cronic_count = hipertension + diabetes + alcoholism chronicGroup = 0 if cronic_count >= -1 or cronic_count < 0: chronicGroup = 0 elif cronic_count == 0 or cronic_count <= 1: chronicGroup = 1 elif cronic_count > 1 or cronic_count <=3: chronicGroup = 2 return np.array([gender, age, neighbourhood, scholarship, hipertension, diabetes, alcoholism, handcap, smsreceived, waitingtime, appointmentDayWeek, waitingGroup, chronicGroup]) class InputData(BaseModel): Gender: str Age: int Neighbourhood: str Scholarship: str Hipertension: str Diabetes: str Alcoholism: str Handcap: str SMSreceived: str WaitingTime: int AppointmentDayOfWeek: int WaitingGroup: str @app.get("/") def home(): return {"Message": "This is an API for no-show prediction"} @app.post("/predict") def prediction(data: InputData): print("Data -> ", data) print("-"*40) raw_data = load_data(data) print("Row Data -> ", raw_data) print("-"*40) scaled_data = scaler.transform(raw_data.reshape(1, -1)) prediction = model.predict(scaled_data) response = {"message": "Data received successfully!", "prediction": "Patient Will No-Show" if int(prediction[0]) == 1 else "Patient Will Show"} return response