Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,44 +4,17 @@ import numpy as np
|
|
| 4 |
import xgboost as xgb
|
| 5 |
import joblib
|
| 6 |
import os
|
| 7 |
-
import time
|
| 8 |
from sklearn.model_selection import train_test_split
|
| 9 |
from sklearn.metrics import accuracy_score, roc_auc_score
|
| 10 |
from sklearn.ensemble import VotingClassifier, RandomForestClassifier
|
| 11 |
from sklearn.linear_model import LogisticRegression
|
| 12 |
from sklearn.preprocessing import StandardScaler
|
| 13 |
from sklearn.pipeline import Pipeline
|
| 14 |
-
from datetime import datetime
|
| 15 |
-
import json
|
| 16 |
-
import re # For email validation
|
| 17 |
-
# NEW: Import HfApi for pushing data to Hugging Face
|
| 18 |
-
try:
|
| 19 |
-
from huggingface_hub import HfApi
|
| 20 |
-
except ImportError:
|
| 21 |
-
# This allows the app to run locally even if the HF libraries are not installed
|
| 22 |
-
class HfApi:
|
| 23 |
-
def upload_file(self, *args, **kwargs):
|
| 24 |
-
print("WARNING: huggingface_hub not imported. HF upload skipped.")
|
| 25 |
-
pass
|
| 26 |
|
| 27 |
-
|
| 28 |
-
# --- 0. Configuration & Tracking ---
|
| 29 |
-
|
| 30 |
-
# IP Usage Limit Configuration
|
| 31 |
-
IP_LIMIT_ENABLED = True # Set to False to disable usage tracking
|
| 32 |
-
IP_MAX_USES = 3 # Max uses allowed per unique IP address
|
| 33 |
-
USER_IP_USAGE = {} # In-memory database to track usage: {ip_address: count}
|
| 34 |
-
|
| 35 |
-
# User Activation Data (Placeholder for Hugging Face)
|
| 36 |
-
USER_DATA_FILE = "user_activations_SalesPilot.csv"
|
| 37 |
-
# Ensure you own/have write access to this dataset repo
|
| 38 |
-
HF_DATASET_REPO = "abhidgp1978/user_activations_SalesPilot"
|
| 39 |
-
|
| 40 |
-
# ML Model/File Configuration
|
| 41 |
MODEL_FILE = "ensemble_model.pkl"
|
| 42 |
SAMPLE_FILE = "sample_leads.csv"
|
|
|
|
| 43 |
HIGH_PRECISION_THRESHOLD = 0.9500
|
| 44 |
-
DEFAULT_THRESHOLD = 0.50
|
| 45 |
|
| 46 |
# ----------------------------
|
| 47 |
# 1. Generate Sample Data (for download)
|
|
@@ -62,28 +35,22 @@ def generate_sample_data(n=150):
|
|
| 62 |
df = pd.DataFrame(data)
|
| 63 |
return df
|
| 64 |
|
| 65 |
-
# Pre-generate sample file
|
| 66 |
if not os.path.exists(SAMPLE_FILE):
|
| 67 |
generate_sample_data(150).to_csv(SAMPLE_FILE, index=False)
|
| 68 |
|
| 69 |
# ----------------------------
|
| 70 |
-
# 2. Model Training
|
| 71 |
# ----------------------------
|
| 72 |
def train_model_from_user_data(file_path):
|
| 73 |
-
# Load data from the user's file which must have a 'Converted' column
|
| 74 |
df = pd.read_csv(file_path)
|
| 75 |
|
| 76 |
-
# Check for required columns
|
| 77 |
-
required_cols = ['Name', 'Converted', 'Industry', 'Job_Title', 'Company_Size', 'Lead_Source']
|
| 78 |
-
if not all(col in df.columns for col in required_cols):
|
| 79 |
-
raise ValueError(f"Missing required columns. Ensure the file contains: {', '.join(required_cols)}")
|
| 80 |
-
|
| 81 |
# Prepare Data
|
| 82 |
X = df.drop(['Name', 'Converted'], axis=1)
|
| 83 |
y = df['Converted']
|
| 84 |
X = pd.get_dummies(X, columns=['Industry', 'Job_Title', 'Lead_Source'], drop_first=True)
|
| 85 |
|
| 86 |
-
#
|
| 87 |
negative_count = (y == 0).sum()
|
| 88 |
positive_count = (y == 1).sum()
|
| 89 |
scale_pos_weight = negative_count / positive_count if positive_count > 0 else 1.0
|
|
@@ -91,381 +58,158 @@ def train_model_from_user_data(file_path):
|
|
| 91 |
# Split data for training/evaluation
|
| 92 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)
|
| 93 |
|
| 94 |
-
# Save feature columns
|
| 95 |
train_cols = X_train.columns.tolist()
|
| 96 |
-
|
| 97 |
-
# Define
|
| 98 |
-
#
|
| 99 |
-
|
| 100 |
-
objective='binary:logistic',
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
random_state=42,
|
| 104 |
-
scale_pos_weight=scale_pos_weight,
|
| 105 |
-
n_estimators=150,
|
| 106 |
-
max_depth=5
|
| 107 |
)
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
('scaler', StandardScaler()),
|
| 115 |
-
('logreg', LogisticRegression(
|
|
|
|
|
|
|
| 116 |
])
|
| 117 |
-
|
| 118 |
-
# Create the
|
| 119 |
-
|
| 120 |
-
ensemble_clf = VotingClassifier(
|
| 121 |
estimators=[
|
| 122 |
-
('xgb',
|
| 123 |
-
('rf',
|
| 124 |
-
('
|
| 125 |
],
|
| 126 |
-
voting='soft',
|
| 127 |
-
|
|
|
|
| 128 |
n_jobs=-1
|
| 129 |
)
|
| 130 |
|
| 131 |
-
|
| 132 |
-
ensemble_clf.fit(X_train, y_train)
|
| 133 |
|
| 134 |
-
|
| 135 |
-
joblib.dump((ensemble_clf, train_cols), MODEL_FILE)
|
| 136 |
|
| 137 |
-
# Evaluate
|
| 138 |
-
y_pred =
|
| 139 |
-
y_proba =
|
| 140 |
accuracy = accuracy_score(y_test, y_pred)
|
| 141 |
auc = roc_auc_score(y_test, y_proba)
|
| 142 |
|
| 143 |
return accuracy, auc
|
| 144 |
|
| 145 |
-
# Check if a model file exists, if not, train a default model
|
| 146 |
-
if not os.path.exists(MODEL_FILE):
|
| 147 |
-
print("No default model found. Training initial Ensemble model...")
|
| 148 |
-
# Train using the default sample data
|
| 149 |
-
generate_sample_data(500).to_csv("default_training.csv", index=False)
|
| 150 |
-
try:
|
| 151 |
-
train_model_from_user_data("default_training.csv")
|
| 152 |
-
except Exception as e:
|
| 153 |
-
print(f"Initial model training failed: {e}")
|
| 154 |
-
finally:
|
| 155 |
-
if os.path.exists("default_training.csv"):
|
| 156 |
-
os.remove("default_training.csv")
|
| 157 |
-
print("Initial model training complete.")
|
| 158 |
-
|
| 159 |
# ----------------------------
|
| 160 |
-
# 3. Lead Prediction
|
| 161 |
# ----------------------------
|
| 162 |
def predict_leads(file_path):
|
| 163 |
-
|
| 164 |
-
return None, None, None, "Error: Model not trained. Please upload data and click 'Retrain Model'.", SAMPLE_FILE, None
|
| 165 |
-
|
| 166 |
-
# Load Model and Feature Columns
|
| 167 |
-
model, train_cols = joblib.load(MODEL_FILE)
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
|
| 173 |
-
|
| 174 |
-
X_new = df_new.drop(['Name'], axis=1, errors='ignore')
|
| 175 |
-
X_new = pd.get_dummies(X_new, columns=['Industry', 'Job_Title', 'Lead_Source'], drop_first=True)
|
| 176 |
|
| 177 |
-
#
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
X_new[c] = 0
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
| 184 |
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
# Define categories based on thresholds
|
| 190 |
-
def get_category(prob):
|
| 191 |
if prob >= HIGH_PRECISION_THRESHOLD:
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
|
|
|
| 195 |
else:
|
| 196 |
-
return
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
#
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
# 3. Summary Output
|
| 211 |
-
summary_data = df_original['AI_Category'].value_counts().reset_index()
|
| 212 |
-
summary_data.columns = ['AI_Category', 'Count']
|
| 213 |
-
|
| 214 |
-
# Use the total number of rows (leads) in the original dataframe
|
| 215 |
-
total_leads = df_original.shape[0]
|
| 216 |
-
summary_data['Percentage'] = (summary_data['Count'] / total_leads * 100).round(1).astype(str) + '%'
|
| 217 |
|
| 218 |
-
# 4. Metrics Output
|
| 219 |
-
model_metrics = f"""
|
| 220 |
-
Model Type: Ensemble Voting Classifier (XGBoost, RF, LogReg)
|
| 221 |
-
XGBoost Weight: 3x (Boosted for Precision)
|
| 222 |
-
High Confidence Threshold: >= {int(HIGH_PRECISION_THRESHOLD * 100)}%
|
| 223 |
-
Default Conversion Threshold: >= {int(DEFAULT_THRESHOLD * 100)}%
|
| 224 |
-
"""
|
| 225 |
-
|
| 226 |
-
# 5. Scored Download File
|
| 227 |
scored_file_name = "scored_leads_ultimate_confidence.csv"
|
| 228 |
-
|
| 229 |
|
| 230 |
-
return
|
| 231 |
-
|
| 232 |
-
# Check if a model file exists, if not, train a default model
|
| 233 |
-
if not os.path.exists(MODEL_FILE):
|
| 234 |
-
print("No default model found. Training initial Ensemble model...")
|
| 235 |
-
# Train using the default sample data
|
| 236 |
-
generate_sample_data(500).to_csv("default_training.csv", index=False)
|
| 237 |
-
try:
|
| 238 |
-
train_model_from_user_data("default_training.csv")
|
| 239 |
-
except Exception as e:
|
| 240 |
-
print(f"Initial model training failed: {e}")
|
| 241 |
-
finally:
|
| 242 |
-
if os.path.exists("default_training.csv"):
|
| 243 |
-
os.remove("default_training.csv")
|
| 244 |
-
print("Initial model training complete.")
|
| 245 |
|
| 246 |
# ----------------------------
|
| 247 |
-
# 4.
|
| 248 |
# ----------------------------
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
"
|
| 252 |
-
try:
|
| 253 |
-
data = {
|
| 254 |
-
'timestamp': datetime.now().isoformat(),
|
| 255 |
-
'name': name,
|
| 256 |
-
'email': email
|
| 257 |
-
}
|
| 258 |
-
|
| 259 |
-
# 1. Save locally to the specified CSV file
|
| 260 |
-
is_new_file = not os.path.exists(USER_DATA_FILE)
|
| 261 |
-
mode = 'a' if not is_new_file else 'w'
|
| 262 |
-
df_new = pd.DataFrame([data])
|
| 263 |
-
df_new.to_csv(USER_DATA_FILE, mode=mode, header=is_new_file, index=False)
|
| 264 |
-
|
| 265 |
-
# 2. Hugging Face Upload Logic
|
| 266 |
-
api = HfApi()
|
| 267 |
-
|
| 268 |
-
# NOTE: For this to work in a deployed environment, you need to ensure
|
| 269 |
-
# that the environment is authenticated to push to HF (e.g., using a
|
| 270 |
-
# set HF_TOKEN environment variable). If you run this locally, you must
|
| 271 |
-
# run `huggingface-cli login` first or set a token in the script.
|
| 272 |
-
try:
|
| 273 |
-
api.upload_file(
|
| 274 |
-
path_or_fileobj=USER_DATA_FILE,
|
| 275 |
-
path_in_repo=USER_DATA_FILE,
|
| 276 |
-
repo_id=HF_DATASET_REPO,
|
| 277 |
-
repo_type="dataset",
|
| 278 |
-
commit_message=f"New user activation by {name} at {datetime.now().isoformat()}"
|
| 279 |
-
)
|
| 280 |
-
hf_status = f"Data successfully uploaded to Hugging Face dataset: `{HF_DATASET_REPO}`."
|
| 281 |
-
except Exception as hf_e:
|
| 282 |
-
hf_status = f"WARNING: Failed to upload data to Hugging Face. Check your token/permissions. Error: {hf_e.__class__.__name__}"
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
return f"Activation successful! User data recorded locally and in memory.\n\n{hf_status}"
|
| 286 |
-
|
| 287 |
-
except Exception as e:
|
| 288 |
-
return f"Activation failed due to data saving error: {e}"
|
| 289 |
-
|
| 290 |
-
def is_valid_email(email):
|
| 291 |
-
"""Simple regex check for email validity."""
|
| 292 |
-
regex = r'^\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
|
| 293 |
-
return re.fullmatch(regex, email)
|
| 294 |
-
|
| 295 |
-
def handle_activation(name, email, current_app_active):
|
| 296 |
-
"""Handles app activation, performing checks inside the function."""
|
| 297 |
-
if current_app_active:
|
| 298 |
-
return gr.update(visible=True), gr.update(visible=False), "App is already active.", True
|
| 299 |
-
|
| 300 |
-
if not name or not email:
|
| 301 |
-
return gr.update(visible=False), gr.update(visible=True), "Error: Name and Email are required.", False
|
| 302 |
-
|
| 303 |
-
if not is_valid_email(email):
|
| 304 |
-
return gr.update(visible=False), gr.update(visible=True), "Error: Please enter a valid email address.", False
|
| 305 |
-
|
| 306 |
-
# Save/log user data (Simulating Hugging Face recording)
|
| 307 |
-
message = save_user_data(name, email)
|
| 308 |
-
|
| 309 |
-
# Activate the main app
|
| 310 |
-
return gr.update(visible=True), gr.update(visible=False), message, True
|
| 311 |
-
|
| 312 |
-
def check_usage_limit(request: gr.Request):
|
| 313 |
-
"""Checks and updates the usage count for the current IP."""
|
| 314 |
-
if not IP_LIMIT_ENABLED:
|
| 315 |
-
return True, "Usage limit check is disabled."
|
| 316 |
-
|
| 317 |
-
# Use request.client.host to get the IP address
|
| 318 |
-
ip = request.client.host
|
| 319 |
-
|
| 320 |
-
# Initialize count if new user
|
| 321 |
-
if ip not in USER_IP_USAGE:
|
| 322 |
-
USER_IP_USAGE[ip] = 0
|
| 323 |
-
|
| 324 |
-
current_uses = USER_IP_USAGE[ip]
|
| 325 |
-
|
| 326 |
-
if current_uses >= IP_MAX_USES:
|
| 327 |
-
return False, f"Usage limit reached! This IP ({ip}) has reached the maximum of {IP_MAX_USES} uses."
|
| 328 |
-
|
| 329 |
-
return True, "" # Successful, return empty message
|
| 330 |
-
|
| 331 |
-
def wrapper_predict(file_path, request: gr.Request):
|
| 332 |
-
"""Wrapper for predict_leads that enforces the usage limit."""
|
| 333 |
-
limit_ok, msg = check_usage_limit(request)
|
| 334 |
-
|
| 335 |
-
if not limit_ok:
|
| 336 |
-
# Return error message if limit is reached
|
| 337 |
-
empty_df = pd.DataFrame()
|
| 338 |
-
return empty_df, empty_df, empty_df, "Prediction failed: Limit Reached.", gr.update(value=SAMPLE_FILE), gr.update(value=None), msg
|
| 339 |
-
|
| 340 |
-
try:
|
| 341 |
-
# Successful execution
|
| 342 |
-
USER_IP_USAGE[request.client.host] += 1
|
| 343 |
-
clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
|
| 344 |
-
|
| 345 |
-
# Keep only the model metrics
|
| 346 |
-
full_metrics = metrics
|
| 347 |
-
|
| 348 |
-
return clean, raw, summary, full_metrics, gr.update(value=sample_file), gr.update(value=scored_file), ""
|
| 349 |
-
except Exception as e:
|
| 350 |
-
# Failed execution, do not increment count
|
| 351 |
-
return pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), f"Prediction failed: {e}", gr.update(value=SAMPLE_FILE), gr.update(value=None), ""
|
| 352 |
-
|
| 353 |
-
def wrapper_retrain(file_path, request: gr.Request):
|
| 354 |
-
"""Wrapper for retrain_model that enforces the usage limit."""
|
| 355 |
-
limit_ok, msg = check_usage_limit(request)
|
| 356 |
-
|
| 357 |
-
if not limit_ok:
|
| 358 |
-
return f"Retraining failed: Limit Reached.", msg
|
| 359 |
-
|
| 360 |
try:
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
acc, auc = train_model_from_user_data(file_path)
|
| 364 |
-
|
| 365 |
-
# Keep only the training metrics
|
| 366 |
-
full_metrics = f"Retrained successfully → Accuracy: {acc:.4f}, AUC: {auc:.4f}"
|
| 367 |
-
|
| 368 |
-
return full_metrics, ""
|
| 369 |
except Exception as e:
|
| 370 |
-
|
| 371 |
-
return f"Retraining failed. Check if your file has the 'Converted' column (0 or 1). Error: {e}", ""
|
| 372 |
-
|
| 373 |
-
# ----------------------------
|
| 374 |
-
# 5. Gradio Interface
|
| 375 |
-
# ----------------------------
|
| 376 |
-
|
| 377 |
-
# Instructions for Tooltip
|
| 378 |
-
INSTRUCTION_STEPS = f"""
|
| 379 |
-
### How to Use the Ultimate Confidence App
|
| 380 |
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
* **Result:** The 'Top 10 Ultimate Confidence Leads' table shows the leads the model is **>95%** sure will convert.
|
| 386 |
-
* **Download:** Use the download button at the bottom to get the full scored list.
|
| 387 |
-
5. **Retrain (Advanced):** If your uploaded file also contains a 'Converted' column (0 for not converted, 1 for converted) from past data, click '🔁 Retrain Model'. This customizes the AI specifically to your company's conversion history.
|
| 388 |
-
"""
|
| 389 |
|
| 390 |
-
with gr.Blocks(title="Ultimate Confidence Lead Scoring") as app:
|
| 391 |
-
|
| 392 |
-
# State variable for managing app activation
|
| 393 |
-
app_active = gr.State(False)
|
| 394 |
-
|
| 395 |
-
gr.Markdown("# 🎯 Ultimate Confidence Lead Targeting")
|
| 396 |
-
gr.Markdown("Stop Chasing, Start Closing. This advanced, multi-model AI system is tuned for high precision, delivering only the short, highly-vetted list of leads who are **most likely to convert right now**.")
|
| 397 |
-
|
| 398 |
-
# --- Tooltip Button & Instructions Group ---
|
| 399 |
with gr.Row():
|
| 400 |
-
gr.
|
| 401 |
-
instructions_btn = gr.Button("❓ How to Use App", scale=0)
|
| 402 |
-
|
| 403 |
-
# Using gr.Group to replace gr.Modal functionality
|
| 404 |
-
with gr.Group(visible=False, elem_id="instructions-group") as instructions_group:
|
| 405 |
-
gr.Markdown("## App Instructions & Usage")
|
| 406 |
-
gr.Markdown(INSTRUCTION_STEPS)
|
| 407 |
-
close_instructions_btn = gr.Button("Close Instructions")
|
| 408 |
-
|
| 409 |
-
# --- Activation Block ---
|
| 410 |
-
with gr.Column(visible=True) as activation_block:
|
| 411 |
-
gr.Markdown("### 🔑 App Activation Required")
|
| 412 |
-
with gr.Row():
|
| 413 |
-
user_name = gr.Textbox(label="Your Name", placeholder="e.g., Jane Doe")
|
| 414 |
-
user_email = gr.Textbox(label="Your Email", placeholder="e.g., jane@company.com")
|
| 415 |
-
|
| 416 |
-
activation_message = gr.Textbox(label="Status", interactive=False)
|
| 417 |
-
activate_btn = gr.Button("🚀 Activate App")
|
| 418 |
-
|
| 419 |
-
# --- Main App Block (Initially Hidden) ---
|
| 420 |
-
with gr.Column(visible=False) as main_app_block:
|
| 421 |
-
|
| 422 |
-
with gr.Row():
|
| 423 |
-
sample_btn = gr.File(label="📥 Download Sample CSV", file_types=[".csv"], value=SAMPLE_FILE)
|
| 424 |
-
|
| 425 |
-
with gr.Row():
|
| 426 |
-
file_input = gr.File(type="filepath", file_types=[".csv"], label="📤 Upload Your Leads CSV")
|
| 427 |
-
predict_btn = gr.Button("🔮 Predict Leads")
|
| 428 |
-
retrain_btn = gr.Button("🔁 Retrain Model Using Uploaded Data")
|
| 429 |
-
|
| 430 |
-
# Outputs
|
| 431 |
-
clean_out = gr.Dataframe(label=f"Top 10 Ultimate Confidence Leads (>= {int(HIGH_PRECISION_THRESHOLD*100)}%)")
|
| 432 |
-
raw_out = gr.Dataframe(label="Raw Predictions (First 10 Rows)")
|
| 433 |
-
summary_out = gr.Dataframe(label="Category Confidence Summary")
|
| 434 |
-
metrics_out = gr.Textbox(label="Model Settings")
|
| 435 |
-
train_metrics = gr.Textbox(label="Retraining Accuracy (Your Data)")
|
| 436 |
-
scored_download = gr.File(label="⬇️ Download Scored Leads CSV (Ultimate Confidence)", file_types=[".csv"])
|
| 437 |
-
|
| 438 |
-
# IP Usage Output (for error/status)
|
| 439 |
-
usage_status_out = gr.Textbox(label="Usage Status Message", interactive=False, visible=False)
|
| 440 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
# Activation Handler
|
| 449 |
-
activate_btn.click(
|
| 450 |
-
fn=handle_activation,
|
| 451 |
-
inputs=[user_name, user_email, app_active],
|
| 452 |
-
outputs=[main_app_block, activation_block, activation_message, app_active],
|
| 453 |
-
)
|
| 454 |
|
| 455 |
-
# Prediction Handler - Gradio automatically passes the Request object as the last argument
|
| 456 |
predict_btn.click(
|
| 457 |
-
fn=
|
| 458 |
-
inputs=[file_input],
|
| 459 |
-
outputs=[clean_out, raw_out, summary_out, metrics_out, sample_btn, scored_download
|
| 460 |
)
|
| 461 |
|
| 462 |
-
# Retraining Handler - Gradio automatically passes the Request object as the last argument
|
| 463 |
retrain_btn.click(
|
| 464 |
-
fn=
|
| 465 |
-
inputs=[file_input],
|
| 466 |
-
outputs=[train_metrics
|
| 467 |
)
|
| 468 |
|
| 469 |
-
# Launch the Gradio app
|
| 470 |
if __name__ == "__main__":
|
| 471 |
-
|
|
|
|
| 4 |
import xgboost as xgb
|
| 5 |
import joblib
|
| 6 |
import os
|
|
|
|
| 7 |
from sklearn.model_selection import train_test_split
|
| 8 |
from sklearn.metrics import accuracy_score, roc_auc_score
|
| 9 |
from sklearn.ensemble import VotingClassifier, RandomForestClassifier
|
| 10 |
from sklearn.linear_model import LogisticRegression
|
| 11 |
from sklearn.preprocessing import StandardScaler
|
| 12 |
from sklearn.pipeline import Pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
MODEL_FILE = "ensemble_model.pkl"
|
| 15 |
SAMPLE_FILE = "sample_leads.csv"
|
| 16 |
+
# RESET: The ultimate threshold is set back to 0.95 to maximize precision.
|
| 17 |
HIGH_PRECISION_THRESHOLD = 0.9500
|
|
|
|
| 18 |
|
| 19 |
# ----------------------------
|
| 20 |
# 1. Generate Sample Data (for download)
|
|
|
|
| 35 |
df = pd.DataFrame(data)
|
| 36 |
return df
|
| 37 |
|
| 38 |
+
# Pre-generate sample file
|
| 39 |
if not os.path.exists(SAMPLE_FILE):
|
| 40 |
generate_sample_data(150).to_csv(SAMPLE_FILE, index=False)
|
| 41 |
|
| 42 |
# ----------------------------
|
| 43 |
+
# 2. Model Training (Ultimate Strategy: Voting Classifier)
|
| 44 |
# ----------------------------
|
| 45 |
def train_model_from_user_data(file_path):
|
|
|
|
| 46 |
df = pd.read_csv(file_path)
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
# Prepare Data
|
| 49 |
X = df.drop(['Name', 'Converted'], axis=1)
|
| 50 |
y = df['Converted']
|
| 51 |
X = pd.get_dummies(X, columns=['Industry', 'Job_Title', 'Lead_Source'], drop_first=True)
|
| 52 |
|
| 53 |
+
# Calculate scale_pos_weight for XGBoost/Class Weighting
|
| 54 |
negative_count = (y == 0).sum()
|
| 55 |
positive_count = (y == 1).sum()
|
| 56 |
scale_pos_weight = negative_count / positive_count if positive_count > 0 else 1.0
|
|
|
|
| 58 |
# Split data for training/evaluation
|
| 59 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)
|
| 60 |
|
|
|
|
| 61 |
train_cols = X_train.columns.tolist()
|
| 62 |
+
|
| 63 |
+
# --- Define Base Estimators (Models) ---
|
| 64 |
+
# NOTE: To boost confidence, we could tune XGBoost here further (e.g., increase min_child_weight)
|
| 65 |
+
xgb_model = xgb.XGBClassifier(
|
| 66 |
+
objective='binary:logistic', use_label_encoder=False, eval_metric='logloss',
|
| 67 |
+
random_state=42, scale_pos_weight=scale_pos_weight, max_depth=3,
|
| 68 |
+
learning_rate=0.1, n_estimators=100
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
)
|
| 70 |
+
|
| 71 |
+
rf_model = RandomForestClassifier(
|
| 72 |
+
n_estimators=100, random_state=42, class_weight='balanced'
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
lr_pipeline = Pipeline([
|
| 76 |
('scaler', StandardScaler()),
|
| 77 |
+
('logreg', LogisticRegression(
|
| 78 |
+
random_state=42, solver='liblinear', class_weight='balanced'
|
| 79 |
+
))
|
| 80 |
])
|
| 81 |
+
|
| 82 |
+
# --- Create the Voting Classifier (Ensemble) ---
|
| 83 |
+
ensemble_model = VotingClassifier(
|
|
|
|
| 84 |
estimators=[
|
| 85 |
+
('xgb', xgb_model),
|
| 86 |
+
('rf', rf_model),
|
| 87 |
+
('lr', lr_pipeline)
|
| 88 |
],
|
| 89 |
+
voting='soft',
|
| 90 |
+
# UPDATED: Increased XGBoost weight from 3 to 7 to let its high conviction dominate the final score
|
| 91 |
+
weights=[7, 1, 1],
|
| 92 |
n_jobs=-1
|
| 93 |
)
|
| 94 |
|
| 95 |
+
ensemble_model.fit(X_train, y_train)
|
|
|
|
| 96 |
|
| 97 |
+
joblib.dump((ensemble_model, train_cols), MODEL_FILE)
|
|
|
|
| 98 |
|
| 99 |
+
# Evaluate Accuracy on Test Set
|
| 100 |
+
y_pred = ensemble_model.predict(X_test)
|
| 101 |
+
y_proba = ensemble_model.predict_proba(X_test)[:, 1]
|
| 102 |
accuracy = accuracy_score(y_test, y_pred)
|
| 103 |
auc = roc_auc_score(y_test, y_proba)
|
| 104 |
|
| 105 |
return accuracy, auc
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
# ----------------------------
|
| 108 |
+
# 3. Lead Prediction
|
| 109 |
# ----------------------------
|
| 110 |
def predict_leads(file_path):
|
| 111 |
+
df_pred = pd.read_csv(file_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
if not os.path.exists(MODEL_FILE):
|
| 114 |
+
return (pd.DataFrame(), pd.DataFrame(), pd.DataFrame({'AI_Category': ['N/A'], 'Count': ['N/A']}),
|
| 115 |
+
"Model not trained. Please retrain using your data first.", SAMPLE_FILE, None)
|
| 116 |
|
| 117 |
+
model, train_cols = joblib.load(MODEL_FILE)
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
# Prepare features, aligning them with the training set
|
| 120 |
+
X_pred = df_pred.drop('Name', axis=1, errors='ignore')
|
| 121 |
+
X_pred = pd.get_dummies(X_pred, columns=['Industry', 'Job_Title', 'Lead_Source'], drop_first=True)
|
|
|
|
| 122 |
|
| 123 |
+
for col in train_cols:
|
| 124 |
+
if col not in X_pred.columns:
|
| 125 |
+
X_pred[col] = 0
|
| 126 |
+
X_pred = X_pred[train_cols]
|
| 127 |
|
| 128 |
+
df_pred['AI_Probability'] = model.predict_proba(X_pred)[:, 1]
|
| 129 |
+
|
| 130 |
+
# Categorization logic using the ultimate 95% threshold
|
| 131 |
+
def categorize(prob):
|
|
|
|
|
|
|
| 132 |
if prob >= HIGH_PRECISION_THRESHOLD:
|
| 133 |
+
# High confidence leads based on the 95% threshold
|
| 134 |
+
return f'Ultimate Confidence (>= {int(HIGH_PRECISION_THRESHOLD*100)}%)'
|
| 135 |
+
elif prob >= 0.5:
|
| 136 |
+
return 'Moderate Lead (Ensemble Consensus)'
|
| 137 |
else:
|
| 138 |
+
return 'Not Preferred'
|
| 139 |
+
|
| 140 |
+
df_pred['AI_Category'] = df_pred['AI_Probability'].apply(categorize)
|
| 141 |
+
|
| 142 |
+
# Generate Output DataFrames
|
| 143 |
+
clean_out = df_pred[['Name', 'AI_Category', 'AI_Probability']].sort_values(by='AI_Probability', ascending=False)
|
| 144 |
+
raw_out = df_pred
|
| 145 |
+
summary_out = df_pred['AI_Category'].value_counts().reset_index(name='Count')
|
| 146 |
+
summary_out.columns = ['AI_Category', 'Count']
|
| 147 |
+
|
| 148 |
+
metrics_text = (
|
| 149 |
+
f"Model: Voting Classifier (XGBoost x7 + RF x1 + LogReg x1)\n"
|
| 150 |
+
f"Ultimate Confidence Threshold: {HIGH_PRECISION_THRESHOLD}"
|
| 151 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
scored_file_name = "scored_leads_ultimate_confidence.csv"
|
| 154 |
+
df_pred.to_csv(scored_file_name, index=False)
|
| 155 |
|
| 156 |
+
return clean_out.head(10), raw_out.head(10), summary_out, metrics_text, SAMPLE_FILE, scored_file_name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
# ----------------------------
|
| 159 |
+
# 4. Initial Setup and Gradio Interface
|
| 160 |
# ----------------------------
|
| 161 |
+
# Check for initial model training
|
| 162 |
+
if not os.path.exists(MODEL_FILE):
|
| 163 |
+
print("Initial model training from sample data...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
try:
|
| 165 |
+
train_model_from_user_data(SAMPLE_FILE)
|
| 166 |
+
print("Ensemble Model trained successfully.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
except Exception as e:
|
| 168 |
+
print(f"Could not train initial model from sample data: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
# Gradio Interface Setup
|
| 171 |
+
with gr.Blocks(title="AI Lead Scoring App (Ultimate Confidence)") as demo:
|
| 172 |
+
gr.Markdown("🎯 Ultimate Confidence Lead Targeting")
|
| 173 |
+
gr.Markdown("Stop Chasing, Start Closing. This advanced, multi-model AI system is tuned for high precision, delivering only the short, highly-vetted list of leads who are **most likely to convert right now")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
with gr.Row():
|
| 176 |
+
sample_btn = gr.File(label="📥 Download Sample CSV", file_types=[".csv"], value=SAMPLE_FILE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
with gr.Row():
|
| 179 |
+
file_input = gr.File(type="filepath", file_types=[".csv"], label="📤 Upload Your Leads CSV")
|
| 180 |
+
predict_btn = gr.Button("🔮 Predict Leads")
|
| 181 |
+
retrain_btn = gr.Button("🔁 Retrain Model Using Uploaded Data")
|
| 182 |
+
|
| 183 |
+
clean_out = gr.Dataframe(label=f"Top 10 Ultimate Confidence Leads (>= {int(HIGH_PRECISION_THRESHOLD*100)}%)")
|
| 184 |
+
raw_out = gr.Dataframe(label="Raw Predictions (First 10 Rows)")
|
| 185 |
+
summary_out = gr.Dataframe(label="Category Confidence Summary")
|
| 186 |
+
metrics_out = gr.Textbox(label="Model Settings")
|
| 187 |
+
train_metrics = gr.Textbox(label="Retraining Accuracy (Your Data)")
|
| 188 |
+
scored_download = gr.File(label="📥 Download Scored Leads CSV (Ultimate Confidence)", file_types=[".csv"])
|
| 189 |
+
|
| 190 |
+
def run_prediction(file_path):
|
| 191 |
+
clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
|
| 192 |
+
# FINAL FIX: Use gr.update() for dynamic component updates
|
| 193 |
+
return clean, raw, summary, metrics, gr.update(value=sample_file), gr.update(value=scored_file)
|
| 194 |
|
| 195 |
+
def retrain_model(file_path):
|
| 196 |
+
try:
|
| 197 |
+
acc, auc = train_model_from_user_data(file_path)
|
| 198 |
+
return f"Retrained successfully → Accuracy: {acc:.4f}, AUC: {auc:.4f}"
|
| 199 |
+
except Exception as e:
|
| 200 |
+
return f"Retraining failed. Check if your file has the 'Converted' column (0 or 1). Error: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
|
|
|
| 202 |
predict_btn.click(
|
| 203 |
+
fn=run_prediction,
|
| 204 |
+
inputs=[file_input],
|
| 205 |
+
outputs=[clean_out, raw_out, summary_out, metrics_out, sample_btn, scored_download]
|
| 206 |
)
|
| 207 |
|
|
|
|
| 208 |
retrain_btn.click(
|
| 209 |
+
fn=retrain_model,
|
| 210 |
+
inputs=[file_input],
|
| 211 |
+
outputs=[train_metrics]
|
| 212 |
)
|
| 213 |
|
|
|
|
| 214 |
if __name__ == "__main__":
|
| 215 |
+
demo.launch()
|