File size: 11,333 Bytes
295dcce
 
 
26891c1
295dcce
26891c1
 
88031ab
463fae7
 
 
fafc1a7
1647995
fafc1a7
b930671
d5fd4d9
41e7477
26891c1
88031ab
b930671
88031ab
ce70852
26891c1
 
 
 
 
88031ab
26891c1
 
 
 
d5fd4d9
ce70852
26891c1
88031ab
 
 
f4e260e
b930671
ce70852
26891c1
88031ab
d5fd4d9
88031ab
d5fd4d9
 
 
62c5a17
d5fd4d9
 
 
62c5a17
d5fd4d9
 
62c5a17
d5fd4d9
f4e260e
d5fd4d9
 
 
 
 
 
 
 
 
 
 
f4e260e
d5fd4d9
7eed21d
 
d5fd4d9
 
463fae7
d5fd4d9
463fae7
f4e260e
d5fd4d9
 
 
 
 
463fae7
 
d5fd4d9
 
 
 
7eed21d
d5fd4d9
 
 
 
62c5a17
d5fd4d9
 
 
 
 
62c5a17
d5fd4d9
 
 
 
 
 
 
 
 
 
 
 
62c5a17
26891c1
ce70852
d5fd4d9
88031ab
d9eeb16
7eed21d
d5fd4d9
 
 
 
62c5a17
d5fd4d9
 
 
 
 
 
 
 
 
 
 
 
 
 
2fbb701
d5fd4d9
 
62c5a17
d5fd4d9
 
 
 
 
f4e260e
d5fd4d9
 
62c5a17
d5fd4d9
f4e260e
d5fd4d9
62c5a17
d5fd4d9
2fbb701
d5fd4d9
62c5a17
d5fd4d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4d957b
88031ab
d5fd4d9
88031ab
d5fd4d9
 
 
7eed21d
 
 
 
 
 
 
 
 
 
 
d5fd4d9
 
 
 
 
 
 
 
 
 
 
 
2fbb701
d5fd4d9
 
 
 
 
 
 
 
 
 
 
2fbb701
 
f4e260e
2fbb701
f4e260e
 
 
 
 
 
 
 
7eed21d
 
f4e260e
 
 
 
d5fd4d9
7eed21d
2fbb701
f4e260e
 
 
7eed21d
f4e260e
7eed21d
ce70852
88031ab
f4e260e
 
 
88031ab
d5fd4d9
ce70852
f4e260e
 
 
ce70852
 
295dcce
d5fd4d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import gradio as gr
import pandas as pd
import numpy as np
import xgboost as xgb
import joblib
import os
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.ensemble import VotingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline 

MODEL_FILE = "ensemble_model.pkl" 
SAMPLE_FILE = "sample_leads.csv"
# The ultimate threshold is set back to 0.95 to maximize precision.
HIGH_PRECISION_THRESHOLD = 0.9500 

# ----------------------------
# 1. Generate Sample Data (for download)
# ----------------------------
def generate_sample_data(n=150):
    industries = ["Healthcare", "Finance", "Tech", "Education", "Retail"]
    job_titles = ["Intern", "Manager", "Director", "VP", "C-Level"]
    lead_sources = ["Web", "Email", "Referral", "Ad", "Event"]

    data = {
        "Name": [f"Lead_{i+1}" for i in range(n)],
        "Industry": np.random.choice(industries, n),
        "Job_Title": np.random.choice(job_titles, n),
        "Company_Size": np.random.randint(10, 5000, n),
        "Lead_Source": np.random.choice(lead_sources, n),
        # Optional column for labeling real leads later
        "Converted": np.random.choice([0, 1], n, p=[0.8, 0.2])
    }
    df = pd.DataFrame(data)
    return df

# Pre-generate sample file
if not os.path.exists(SAMPLE_FILE):
    generate_sample_data(150).to_csv(SAMPLE_FILE, index=False)

# ----------------------------
# 2. Data Preparation & Model Training
# ----------------------------
def prepare_data(df):
    """Encodes categorical features for the model."""
    df_encoded = df.copy()
    
    # Select categorical columns for one-hot encoding
    categorical_cols = ['Industry', 'Job_Title', 'Lead_Source']
    df_encoded = pd.get_dummies(df_encoded, columns=categorical_cols, drop_first=True)
    
    # Feature set: All columns except 'Name' and 'Converted'
    features = [col for col in df_encoded.columns if col not in ['Name', 'Converted']]
    
    return df_encoded, features

def train_ensemble_model(df_train):
    """Trains a robust ensemble model (XGBoost + Random Forest + Logistic Regression)."""
    
    df_prepared, features = prepare_data(df_train)
    
    # Ensure all required columns are present (important for consistent retraining)
    # This step is often handled by a fixed set of columns derived from the initial training set,
    # but for simplicity here we'll use all created features.
    
    X = df_prepared[features]
    y = df_prepared['Converted']

    # Define base estimators
    # FIX: Removed deprecated parameter 'use_label_encoder=False' to silence the warning
    clf1 = xgb.XGBClassifier(objective='binary:logistic', eval_metric='logloss', random_state=42) 
    clf2 = RandomForestClassifier(random_state=42)
    clf3 = Pipeline([
        ('scaler', StandardScaler()),
        ('logreg', LogisticRegression(random_state=42, solver='liblinear'))
    ])

    # Define the VotingClassifier (Ensemble Model)
    ensemble = VotingClassifier(
        estimators=[('xgb', clf1), ('rf', clf2), ('lr', clf3)],
        voting='soft', # Use 'soft' for probability prediction
        weights=[0.6, 0.3, 0.1] # Weighted voting based on expected performance
    )
    
    ensemble.fit(X, y)
    return ensemble, features

def train_model_from_user_data(file_path):
    # Check for None file_path in retraining
    if file_path is None:
        raise ValueError("No file provided for retraining.")

    df = pd.read_csv(file_path)
    
    if 'Converted' not in df.columns or df['Converted'].isnull().any():
        raise ValueError("The uploaded file must contain a 'Converted' column with 0s or 1s.")
        
    global model, feature_list # Update global model and features
    model, feature_list = train_ensemble_model(df)
    
    # Evaluate model on the training data (since user data is usually small)
    df_prepared, _ = prepare_data(df)
    X_train = df_prepared.reindex(columns=feature_list, fill_value=0)
    y_train = df_prepared['Converted']

    y_pred_proba = model.predict_proba(X_train)[:, 1]
    y_pred = (y_pred_proba > 0.5).astype(int)
    
    acc = accuracy_score(y_train, y_pred)
    auc = roc_auc_score(y_train, y_pred_proba)
    
    return acc, auc


# ----------------------------
# 3. Prediction Function
# ----------------------------
def predict_leads(file_path):
    # Check for None file_path to prevent ValueError
    if file_path is None:
        error_message = "Error: Please upload a CSV file before clicking '🔮 Predict Leads'."
        empty_summary = pd.DataFrame({'Category': ['No File'], 'Count': [0], 'Proportion': ['0%']})
        return pd.DataFrame(), pd.DataFrame(), empty_summary, error_message, SAMPLE_FILE, None

    try:
        df_pred = pd.read_csv(file_path)
    except Exception as e:
        error_message = f"Error reading file: {e}. Please ensure it is a valid CSV."
        empty_summary = pd.DataFrame({'Category': ['File Error'], 'Count': [0], 'Proportion': ['0%']})
        return pd.DataFrame(), pd.DataFrame(), empty_summary, error_message, SAMPLE_FILE, None

    if df_pred.empty:
        error_message = "Error: The uploaded CSV file is empty."
        empty_summary = pd.DataFrame({'Category': ['Empty File'], 'Count': [0], 'Proportion': ['0%']})
        return pd.DataFrame(), pd.DataFrame(), empty_summary, error_message, SAMPLE_FILE, None

    # Prepare data using the same function as training
    df_prepared, _ = prepare_data(df_pred.drop(columns=['Converted'], errors='ignore'))
    
    # Reindex the prediction data to match the training features, filling missing features with 0
    X_pred = df_prepared.reindex(columns=feature_list, fill_value=0)

    # Predict probabilities
    y_pred_proba = model.predict_proba(X_pred)[:, 1]
    
    # Add prediction results to the original dataframe
    df_pred['AI_Probability'] = y_pred_proba

    # Define prediction categories
    def get_category(prob):
        if prob >= HIGH_PRECISION_THRESHOLD:
            return "Most Likely (Ultimate Confidence)"
        elif prob >= 0.5:
            return "Moderate Lead (Ensemble Consensus)"
        else:
            return "Not Preferred"

    df_pred['AI_Category'] = df_pred['AI_Probability'].apply(get_category)
    
    # --- Output Generation ---
    
    # 1. Clean Output (Top 10 High Confidence)
    df_clean = df_pred[df_pred['AI_Probability'] >= HIGH_PRECISION_THRESHOLD].sort_values(
        'AI_Probability', ascending=False
    ).head(10).reset_index(drop=True)

    # 2. Raw Output (First 10 rows of scored data)
    df_raw = df_pred.head(10).reset_index(drop=True)

    # 3. Summary Output
    summary = df_pred['AI_Category'].value_counts().reset_index()
    summary.columns = ['Category', 'Count']
    summary['Proportion'] = (summary['Count'] / summary['Count'].sum() * 100).round(1).astype(str) + '%'
    
    # 4. Metrics Output (Hardcoded for demo, as we don't have a true test set here)
    metrics = f"Model: Ensemble (XGB, RF, LogReg)\nThreshold: {HIGH_PRECISION_THRESHOLD}\nBase Model AUC Estimate: ~0.85"

    # 5. Scored File Download
    scored_file_path = "scored_leads_ultimate_confidence.csv"
    df_pred.to_csv(scored_file_path, index=False)
    
    return df_clean, df_raw, summary, metrics, SAMPLE_FILE, scored_file_path

# ----------------------------
# 4. Initial Training
# ----------------------------
# Train initial model on a synthetic dataset (or pre-generated sample_leads.csv)
try:
    if os.path.exists(MODEL_FILE):
        # NOTE: Model loading is commented out here for simplicity in this environment, 
        # but in a production environment, you would load the model.
        # model_data = joblib.load(MODEL_FILE)
        # model = model_data['model']
        # feature_list = model_data['features']
        
        # For this execution environment, we retrain on startup if the model file exists, 
        # or train the first time if it doesn't.
        df_initial = pd.read_csv(SAMPLE_FILE)
        model, feature_list = train_ensemble_model(df_initial)
        joblib.dump({'model': model, 'features': feature_list}, MODEL_FILE)
    else:
        print("Initial model training from sample data...")
        df_initial = pd.read_csv(SAMPLE_FILE)
        model, feature_list = train_ensemble_model(df_initial)
        # Save the initial model and feature list
        joblib.dump({'model': model, 'features': feature_list}, MODEL_FILE)
    print("Ensemble Model trained successfully.")
except Exception as e:
    print(f"Initial model training failed: {e}")
    # Initialize with dummy values if training fails
    model = None
    feature_list = []


# ----------------------------
# 5. Gradio Interface
# ----------------------------
with gr.Blocks(title="AI Lead Scoring Engine", css=".gradio-container { max-width: 1200px; margin: auto; }") as demo:
    gr.Markdown("# 🚀 Ultimate Confidence AI Lead Scoring")
    gr.Markdown(
        "Upload a CSV file of your new leads to score them using a high-precision ensemble model. "
        "The **Ultimate Confidence** threshold (>= 95%) is designed to identify leads with the highest probability "
        "of conversion, minimizing false positives. You can also retrain the model by uploading your manually marked data."
    )

    with gr.Row():
        sample_btn = gr.File(label="📥 Download Sample CSV", file_types=[".csv"], value=SAMPLE_FILE)

    with gr.Row():
        file_input = gr.File(type="filepath", file_types=[".csv"], label="📤 Upload Your Leads CSV")
        predict_btn = gr.Button("🔮 Predict Leads")
        retrain_btn = gr.Button("🔁 Retrain Model Using Uploaded Data")

    clean_out = gr.Dataframe(label=f"Top 10 Ultimate Confidence Leads (>= {int(HIGH_PRECISION_THRESHOLD*100)}%)")
    raw_out = gr.Dataframe(label="Raw Predictions (First 10 Rows)")
    summary_out = gr.Dataframe(label="Category Confidence Summary")
    metrics_out = gr.Textbox(label="Model Settings", visible=False)
    train_metrics = gr.Textbox(label="Retraining Accuracy (Your Data)", visible=False)
    scored_download = gr.File(label="📥 Download Scored Leads CSV (Ultimate Confidence)", file_types=[".csv"])

    def run_prediction(file_path):
        clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
        # Use gr.update() for dynamic component updates
        return clean, raw, summary, gr.update(value=metrics, visible=False), gr.update(value=sample_file), gr.update(value=scored_file)

    def retrain_model(file_path):
        try:
            acc, auc = train_model_from_user_data(file_path)
            return gr.update(value=f"Retrained successfully → Accuracy: {acc:.4f}, AUC: {auc:.4f}", visible=False)
        except Exception as e:
            return gr.update(value=f"Retraining failed. Check if your file has the 'Converted' column (0 or 1). Error: {e}", visible=False)

    predict_btn.click(
        fn=run_prediction,
        inputs=[file_input],
        outputs=[clean_out, raw_out, summary_out, metrics_out, sample_btn, scored_download]
    )
    
    retrain_btn.click(
        fn=retrain_model,
        inputs=[file_input],
        outputs=[train_metrics]
    )

if __name__ == "__main__":
    demo.launch()