import gradio as gr import pandas as pd import joblib import os # Define file paths for the model and encoder MODEL_PATH = "churnaizer_saas_model.pkl" # ENCODER_PATH = "one_hot_encoder.pkl" # Load the model and encoder try: model = joblib.load(MODEL_PATH) # encoder = joblib.load(ENCODER_PATH) except FileNotFoundError: raise FileNotFoundError("Model file not found. Please ensure 'churnaizer_saas_model.pkl' is in the same directory as app.py") # def preprocess_data(df): # # Identify categorical and numerical columns based on the encoder's features # categorical_features = encoder.named_transformers_['cat'].get_feature_names_out(input_features=['last_payment_status', 'subscription_plan']) # numerical_features = [col for col in df.columns if col not in ['last_payment_status', 'subscription_plan']] # # Apply the encoder # processed_data = encoder.transform(df) # # Create a DataFrame from the processed data with correct column names # processed_df = pd.DataFrame(processed_data, columns=list(numerical_features) + list(categorical_features)) # return processed_df def predict_churn(csv_file): if csv_file is None: return "Please upload a CSV file." try: df = pd.read_csv(csv_file.name) # Preprocess the data # processed_df = preprocess_data(df.copy()) # Make predictions predictions = model.predict(df) prediction_proba = model.predict_proba(df)[:, 1] # Probability of churn # Add predictions to the original DataFrame df["churn_prediction"] = predictions df["churn_probability"] = prediction_proba return df except Exception as e: return f"An error occurred during prediction: {e}" # Gradio Interface iface = gr.Interface( fn=predict_churn, inputs=gr.File(label="Upload CSV for Churn Prediction"), outputs=gr.Dataframe(label="Churn Predictions"), title="Churn Prediction App", description="Upload a CSV file to get churn predictions. The output will include the original data with 'churn_prediction' (0 or 1) and 'churn_probability' columns added." ) if __name__ == "__main__": iface.launch(share=True)