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()