Spaces:
Sleeping
Sleeping
import gradio as gr | |
import xgboost as xgb | |
import numpy as np | |
import pickle | |
import json | |
import requests | |
# Load pre-trained model | |
model = pickle.load(open("lapse_model.pkl", "rb")) | |
# Salesforce (Optional - replace with your actual endpoint and secure token handling!) | |
SALESFORCE_ENDPOINT = "https://orgfarm-ac78ff910d-dev-ed.develop.lightning.force.com/services/data/vXX.0/sobjects/Lapse_Risk__c/" | |
SALESFORCE_AUTH_TOKEN = "Bearer YOUR_SALESFORCE_TOKEN" # Use environment variable in production! | |
def predict_lapse(policy_id, last_premium_paid_date, payment_mode, policy_term, policy_age, communication_score): | |
# Map payment_mode to numeric | |
payment_map = {"Annual": 0, "Semi-Annual": 1, "Quarterly": 2, "Monthly": 3} | |
payment_encoded = payment_map.get(payment_mode, 0) | |
# Create feature array with 4 features | |
features = np.array([[policy_term, policy_age, payment_encoded, communication_score]]) | |
# Predict lapse risk | |
try: | |
risk_score = model.predict_proba(features)[0][1] | |
except Exception as e: | |
return f"Prediction failed: {e}" | |
# OPTIONAL: Send to Salesforce | |
try: | |
headers = { | |
"Authorization": SALESFORCE_AUTH_TOKEN, | |
"Content-Type": "application/json" | |
} | |
data = { | |
"Name": policy_id, | |
"Lapse_Risk_Score__c": risk_score, | |
"Last_Paid_Date__c": last_premium_paid_date, | |
"Premium_Payment_Mode__c": payment_mode, | |
"Policy_Term__c": policy_term, | |
"Policy_Age__c": policy_age, | |
"Communication_Score__c": communication_score | |
} | |
response = requests.post(SALESFORCE_ENDPOINT, json=data, headers=headers) | |
print("Salesforce Response:", response.status_code, response.text) | |
except Exception as e: | |
print("Salesforce Integration Error:", e) | |
return round(risk_score, 3) | |
# Gradio UI | |
demo = gr.Interface( | |
fn=predict_lapse, | |
inputs=[ | |
gr.Text(label="Policy ID"), | |
gr.Text(label="Last Premium Paid Date (YYYY-MM-DD)"), | |
gr.Dropdown(["Annual", "Semi-Annual", "Quarterly", "Monthly"], label="Payment Mode"), | |
gr.Number(label="Policy Term (Years)"), | |
gr.Number(label="Policy Age (Years)"), | |
gr.Slider(0, 1, step=0.01, label="Communication Score (0 to 1)") | |
], | |
outputs=gr.Number(label="Lapse Risk Score (0 - 1)"), | |
title="Lapse Risk Predictor", | |
description="Predict the likelihood of policy lapse using XGBoost model" | |
) | |
demo.launch() | |