Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,17 +4,33 @@ import numpy as np
|
|
| 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,22 +51,28 @@ def generate_sample_data(n=150):
|
|
| 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
|
| 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 |
-
#
|
| 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,158 +80,334 @@ def train_model_from_user_data(file_path):
|
|
| 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 |
-
#
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
objective='binary:logistic',
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
)
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
('scaler', StandardScaler()),
|
| 77 |
-
('logreg', LogisticRegression(
|
| 78 |
-
random_state=42, solver='liblinear', class_weight='balanced'
|
| 79 |
-
))
|
| 80 |
])
|
| 81 |
-
|
| 82 |
-
#
|
| 83 |
-
|
|
|
|
| 84 |
estimators=[
|
| 85 |
-
('xgb',
|
| 86 |
-
('rf',
|
| 87 |
-
('
|
| 88 |
],
|
| 89 |
-
voting='soft',
|
| 90 |
-
|
| 91 |
-
weights=[7, 1, 1],
|
| 92 |
n_jobs=-1
|
| 93 |
)
|
| 94 |
|
| 95 |
-
|
|
|
|
| 96 |
|
| 97 |
-
|
|
|
|
| 98 |
|
| 99 |
-
# Evaluate
|
| 100 |
-
y_pred =
|
| 101 |
-
y_proba =
|
| 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
|
| 115 |
-
"Model not trained. Please retrain using your data first.", SAMPLE_FILE, None)
|
| 116 |
-
|
| 117 |
-
model, train_cols = joblib.load(MODEL_FILE)
|
| 118 |
|
| 119 |
-
#
|
| 120 |
-
|
| 121 |
-
X_pred = pd.get_dummies(X_pred, columns=['Industry', 'Job_Title', 'Lead_Source'], drop_first=True)
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
X_pred = X_pred[train_cols]
|
| 127 |
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
#
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
if prob >= HIGH_PRECISION_THRESHOLD:
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
return 'Moderate Lead (Ensemble Consensus)'
|
| 137 |
else:
|
| 138 |
-
return
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
#
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
)
|
| 152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
scored_file_name = "scored_leads_ultimate_confidence.csv"
|
| 154 |
-
|
| 155 |
|
| 156 |
-
return
|
| 157 |
|
| 158 |
# ----------------------------
|
| 159 |
-
# 4.
|
| 160 |
# ----------------------------
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
try:
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
except Exception as e:
|
| 168 |
-
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
|
|
|
| 202 |
predict_btn.click(
|
| 203 |
-
fn=
|
| 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=
|
| 210 |
-
inputs=[file_input],
|
| 211 |
-
outputs=[train_metrics]
|
| 212 |
)
|
| 213 |
|
|
|
|
| 214 |
if __name__ == "__main__":
|
| 215 |
-
|
|
|
|
|
|
| 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 |
|
| 18 |
+
# --- 0. Configuration & Tracking (UPDATED: Filename) ---
|
| 19 |
+
|
| 20 |
+
# IP Usage Limit Configuration
|
| 21 |
+
IP_LIMIT_ENABLED = True # Set to False to disable usage tracking
|
| 22 |
+
IP_MAX_USES = 3 # Max uses allowed per unique IP address
|
| 23 |
+
USER_IP_USAGE = {} # In-memory database to track usage: {ip_address: count}
|
| 24 |
+
|
| 25 |
+
# User Activation Data (Placeholder for Hugging Face)
|
| 26 |
+
USER_DATA_FILE = "user_activations_SalesPilot.csv" # <--- UPDATED FILENAME
|
| 27 |
+
HF_DATASET_REPO = "abhidgp1978/datasets" # Placeholder for desired upload location
|
| 28 |
+
|
| 29 |
+
# ML Model/File Configuration
|
| 30 |
MODEL_FILE = "ensemble_model.pkl"
|
| 31 |
SAMPLE_FILE = "sample_leads.csv"
|
|
|
|
| 32 |
HIGH_PRECISION_THRESHOLD = 0.9500
|
| 33 |
+
DEFAULT_THRESHOLD = 0.50
|
| 34 |
|
| 35 |
# ----------------------------
|
| 36 |
# 1. Generate Sample Data (for download)
|
|
|
|
| 51 |
df = pd.DataFrame(data)
|
| 52 |
return df
|
| 53 |
|
| 54 |
+
# Pre-generate sample file (ensure a default file exists)
|
| 55 |
if not os.path.exists(SAMPLE_FILE):
|
| 56 |
generate_sample_data(150).to_csv(SAMPLE_FILE, index=False)
|
| 57 |
|
| 58 |
# ----------------------------
|
| 59 |
+
# 2. Model Training
|
| 60 |
# ----------------------------
|
| 61 |
def train_model_from_user_data(file_path):
|
| 62 |
+
# Load data from the user's file which must have a 'Converted' column
|
| 63 |
df = pd.read_csv(file_path)
|
| 64 |
|
| 65 |
+
# Check for required columns
|
| 66 |
+
required_cols = ['Name', 'Converted', 'Industry', 'Job_Title', 'Company_Size', 'Lead_Source']
|
| 67 |
+
if not all(col in df.columns for col in required_cols):
|
| 68 |
+
raise ValueError(f"Missing required columns. Ensure the file contains: {', '.join(required_cols)}")
|
| 69 |
+
|
| 70 |
# Prepare Data
|
| 71 |
X = df.drop(['Name', 'Converted'], axis=1)
|
| 72 |
y = df['Converted']
|
| 73 |
X = pd.get_dummies(X, columns=['Industry', 'Job_Title', 'Lead_Source'], drop_first=True)
|
| 74 |
|
| 75 |
+
# Handle class imbalance (important for precision/recall balance)
|
| 76 |
negative_count = (y == 0).sum()
|
| 77 |
positive_count = (y == 1).sum()
|
| 78 |
scale_pos_weight = negative_count / positive_count if positive_count > 0 else 1.0
|
|
|
|
| 80 |
# Split data for training/evaluation
|
| 81 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)
|
| 82 |
|
| 83 |
+
# Save feature columns
|
| 84 |
train_cols = X_train.columns.tolist()
|
| 85 |
+
|
| 86 |
+
# Define the base models for the Ensemble Voting Classifier
|
| 87 |
+
# 1. XGBoost (strong classification base)
|
| 88 |
+
xgb_clf = xgb.XGBClassifier(
|
| 89 |
+
objective='binary:logistic',
|
| 90 |
+
use_label_encoder=False,
|
| 91 |
+
eval_metric='logloss',
|
| 92 |
+
random_state=42,
|
| 93 |
+
scale_pos_weight=scale_pos_weight,
|
| 94 |
+
n_estimators=150,
|
| 95 |
+
max_depth=5
|
| 96 |
)
|
| 97 |
+
|
| 98 |
+
# 2. Random Forest
|
| 99 |
+
rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)
|
| 100 |
+
|
| 101 |
+
# 3. Logistic Regression (simple linear base)
|
| 102 |
+
log_clf = Pipeline([
|
| 103 |
('scaler', StandardScaler()),
|
| 104 |
+
('logreg', LogisticRegression(solver='liblinear', random_state=42))
|
|
|
|
|
|
|
| 105 |
])
|
| 106 |
+
|
| 107 |
+
# Create the Ensemble Voting Classifier
|
| 108 |
+
# Weights are boosted towards XGBoost for maximum confidence/precision
|
| 109 |
+
ensemble_clf = VotingClassifier(
|
| 110 |
estimators=[
|
| 111 |
+
('xgb', xgb_clf),
|
| 112 |
+
('rf', rf_clf),
|
| 113 |
+
('log', log_clf)
|
| 114 |
],
|
| 115 |
+
voting='soft',
|
| 116 |
+
weights=[3, 1, 1], # Boosted weight for the XGBoost model
|
|
|
|
| 117 |
n_jobs=-1
|
| 118 |
)
|
| 119 |
|
| 120 |
+
# Train the Ensemble Model
|
| 121 |
+
ensemble_clf.fit(X_train, y_train)
|
| 122 |
|
| 123 |
+
# Save the model and feature columns
|
| 124 |
+
joblib.dump((ensemble_clf, train_cols), MODEL_FILE)
|
| 125 |
|
| 126 |
+
# Evaluate Metrics on Test Set
|
| 127 |
+
y_pred = ensemble_clf.predict(X_test)
|
| 128 |
+
y_proba = ensemble_clf.predict_proba(X_test)[:, 1]
|
| 129 |
accuracy = accuracy_score(y_test, y_pred)
|
| 130 |
auc = roc_auc_score(y_test, y_proba)
|
| 131 |
|
| 132 |
return accuracy, auc
|
| 133 |
|
| 134 |
+
# Check if a model file exists, if not, train a default model
|
| 135 |
+
if not os.path.exists(MODEL_FILE):
|
| 136 |
+
print("No default model found. Training initial Ensemble model...")
|
| 137 |
+
# Train using the default sample data
|
| 138 |
+
generate_sample_data(500).to_csv("default_training.csv", index=False)
|
| 139 |
+
train_model_from_user_data("default_training.csv")
|
| 140 |
+
os.remove("default_training.csv")
|
| 141 |
+
print("Initial model training complete.")
|
| 142 |
+
|
| 143 |
# ----------------------------
|
| 144 |
+
# 3. Lead Prediction
|
| 145 |
# ----------------------------
|
| 146 |
def predict_leads(file_path):
|
|
|
|
|
|
|
| 147 |
if not os.path.exists(MODEL_FILE):
|
| 148 |
+
return None, None, None, "Error: Model not trained. Please upload data and click 'Retrain Model'.", SAMPLE_FILE, None
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
# Load Model and Feature Columns
|
| 151 |
+
model, train_cols = joblib.load(MODEL_FILE)
|
|
|
|
| 152 |
|
| 153 |
+
# Load new leads data
|
| 154 |
+
df_new = pd.read_csv(file_path)
|
| 155 |
+
df_original = df_new.copy()
|
|
|
|
| 156 |
|
| 157 |
+
# Preprocess leads
|
| 158 |
+
X_new = df_new.drop(['Name'], axis=1, errors='ignore')
|
| 159 |
+
X_new = pd.get_dummies(X_new, columns=['Industry', 'Job_Title', 'Lead_Source'], drop_first=True)
|
| 160 |
+
|
| 161 |
+
# Align columns with training data (critical for model stability)
|
| 162 |
+
missing_cols = set(train_cols) - set(X_new.columns)
|
| 163 |
+
for c in missing_cols:
|
| 164 |
+
X_new[c] = 0
|
| 165 |
+
|
| 166 |
+
# Drop columns not in training data and ensure order
|
| 167 |
+
X_new = X_new[train_cols]
|
| 168 |
|
| 169 |
+
# Predict probabilities
|
| 170 |
+
probabilities = model.predict_proba(X_new)[:, 1]
|
| 171 |
+
df_original['AI_Probability'] = probabilities
|
| 172 |
+
|
| 173 |
+
# Define categories based on thresholds
|
| 174 |
+
def get_category(prob):
|
| 175 |
if prob >= HIGH_PRECISION_THRESHOLD:
|
| 176 |
+
return f"Most Likely (Ultimate Confidence)"
|
| 177 |
+
elif prob >= DEFAULT_THRESHOLD:
|
| 178 |
+
return f"Moderate Lead (Ensemble Consensus)"
|
|
|
|
| 179 |
else:
|
| 180 |
+
return "Not Preferred"
|
| 181 |
+
|
| 182 |
+
df_original['AI_Category'] = df_original['AI_Probability'].apply(get_category)
|
| 183 |
+
|
| 184 |
+
# --- Output Generation ---
|
| 185 |
+
|
| 186 |
+
# 1. Clean Output (Top 10 High Confidence Leads)
|
| 187 |
+
clean_df = df_original[df_original['AI_Probability'] >= HIGH_PRECISION_THRESHOLD].sort_values(
|
| 188 |
+
by='AI_Probability', ascending=False
|
| 189 |
+
).head(10).drop(columns=['Converted'], errors='ignore')
|
| 190 |
+
|
| 191 |
+
# 2. Raw Predictions (First 10 Rows)
|
| 192 |
+
raw_df = df_original.head(10).drop(columns=['Converted'], errors='ignore')
|
|
|
|
| 193 |
|
| 194 |
+
# 3. Summary Output
|
| 195 |
+
summary_data = df_original['AI_Category'].value_counts().reset_index()
|
| 196 |
+
summary_data.columns = ['AI_Category', 'Count']
|
| 197 |
+
summary_data['Percentage'] = (summary_data['Count'] / summary_data['Count'].sum() * 100).round(1).astype(str) + '%'
|
| 198 |
+
|
| 199 |
+
# 4. Metrics Output
|
| 200 |
+
model_metrics = f"""
|
| 201 |
+
Model Type: Ensemble Voting Classifier (XGBoost, RF, LogReg)
|
| 202 |
+
XGBoost Weight: 3x (Boosted for Precision)
|
| 203 |
+
High Confidence Threshold: >= {int(HIGH_PRECISION_THRESHOLD * 100)}%
|
| 204 |
+
Default Conversion Threshold: >= {int(DEFAULT_THRESHOLD * 100)}%
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
# 5. Scored Download File
|
| 208 |
scored_file_name = "scored_leads_ultimate_confidence.csv"
|
| 209 |
+
df_original.to_csv(scored_file_name, index=False)
|
| 210 |
|
| 211 |
+
return clean_df, raw_df, summary_data, model_metrics, SAMPLE_FILE, scored_file_name
|
| 212 |
|
| 213 |
# ----------------------------
|
| 214 |
+
# 4. Activation and Tracking Functions
|
| 215 |
# ----------------------------
|
| 216 |
+
|
| 217 |
+
def save_user_data(name, email):
|
| 218 |
+
"""Placeholder function to simulate saving data for Hugging Face dataset."""
|
| 219 |
try:
|
| 220 |
+
data = {
|
| 221 |
+
'timestamp': datetime.now().isoformat(),
|
| 222 |
+
'name': name,
|
| 223 |
+
'email': email
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
# Save to the specified CSV file
|
| 227 |
+
mode = 'a' if os.path.exists(USER_DATA_FILE) else 'w'
|
| 228 |
+
df_new = pd.DataFrame([data])
|
| 229 |
+
df_new.to_csv(USER_DATA_FILE, mode=mode, header=mode=='w', index=False)
|
| 230 |
+
|
| 231 |
+
return f"Activation successful. User data recorded in '{USER_DATA_FILE}' (simulating upload to {HF_DATASET_REPO})."
|
| 232 |
except Exception as e:
|
| 233 |
+
return f"Activation failed due to data saving error: {e}"
|
| 234 |
|
| 235 |
+
def is_valid_email(email):
|
| 236 |
+
"""Simple regex check for email validity."""
|
| 237 |
+
regex = r'^\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
|
| 238 |
+
return re.fullmatch(regex, email)
|
| 239 |
|
| 240 |
+
def handle_activation(name, email):
|
| 241 |
+
if not name or not email:
|
| 242 |
+
return gr.update(visible=False), gr.update(visible=True), "Error: Name and Email are required.", False
|
| 243 |
+
|
| 244 |
+
if not is_valid_email(email):
|
| 245 |
+
return gr.update(visible=False), gr.update(visible=True), "Error: Please enter a valid email address.", False
|
| 246 |
+
|
| 247 |
+
# Save/log user data (Simulating Hugging Face recording)
|
| 248 |
+
message = save_user_data(name, email)
|
| 249 |
+
|
| 250 |
+
# Activate the main app
|
| 251 |
+
return gr.update(visible=True), gr.update(visible=False), message, True
|
| 252 |
|
| 253 |
+
def check_usage_limit(request: gr.Request):
|
| 254 |
+
"""Checks and updates the usage count for the current IP."""
|
| 255 |
+
if not IP_LIMIT_ENABLED:
|
| 256 |
+
return True, "Usage limit check is disabled."
|
| 257 |
+
|
| 258 |
+
# Use request.client.host to get the IP address
|
| 259 |
+
ip = request.client.host
|
| 260 |
+
|
| 261 |
+
# Initialize count if new user
|
| 262 |
+
if ip not in USER_IP_USAGE:
|
| 263 |
+
USER_IP_USAGE[ip] = 0
|
| 264 |
+
|
| 265 |
+
current_uses = USER_IP_USAGE[ip]
|
| 266 |
+
|
| 267 |
+
if current_uses >= IP_MAX_USES:
|
| 268 |
+
return False, f"Usage limit reached! This IP ({ip}) has reached the maximum of {IP_MAX_USES} uses."
|
| 269 |
+
|
| 270 |
+
return True, f"Uses remaining for IP {ip}: {IP_MAX_USES - current_uses}"
|
| 271 |
+
|
| 272 |
+
def wrapper_predict(file_path, request: gr.Request):
|
| 273 |
+
"""Wrapper for predict_leads that enforces the usage limit."""
|
| 274 |
+
limit_ok, msg = check_usage_limit(request)
|
| 275 |
+
|
| 276 |
+
if not limit_ok:
|
| 277 |
+
# Return error message for all outputs
|
| 278 |
+
empty_df = pd.DataFrame()
|
| 279 |
+
return empty_df, empty_df, empty_df, msg, gr.update(value=SAMPLE_FILE), gr.update(value=None), msg
|
| 280 |
+
|
| 281 |
+
try:
|
| 282 |
+
# Successful execution
|
| 283 |
+
USER_IP_USAGE[request.client.host] += 1
|
| 284 |
clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
|
| 285 |
+
|
| 286 |
+
# Display IP usage status along with model metrics
|
| 287 |
+
full_metrics = f"{metrics.strip()}\n----------------------------\nUsage Status: {msg.split(':')[-1].strip()} use(s) left."
|
| 288 |
+
|
| 289 |
+
return clean, raw, summary, full_metrics, gr.update(value=sample_file), gr.update(value=scored_file), ""
|
| 290 |
+
except Exception as e:
|
| 291 |
+
# Failed execution, do not increment count
|
| 292 |
+
return pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), f"Prediction failed: {e}", gr.update(value=SAMPLE_FILE), gr.update(value=None), ""
|
| 293 |
+
|
| 294 |
+
def wrapper_retrain(file_path, request: gr.Request):
|
| 295 |
+
"""Wrapper for retrain_model that enforces the usage limit."""
|
| 296 |
+
limit_ok, msg = check_usage_limit(request)
|
| 297 |
+
|
| 298 |
+
if not limit_ok:
|
| 299 |
+
return f"Retraining failed: {msg}", msg
|
| 300 |
+
|
| 301 |
+
try:
|
| 302 |
+
# Successful execution
|
| 303 |
+
USER_IP_USAGE[request.client.host] += 1
|
| 304 |
+
acc, auc = train_model_from_user_data(file_path)
|
| 305 |
+
|
| 306 |
+
# Display IP usage status along with training metrics
|
| 307 |
+
full_metrics = f"Retrained successfully → Accuracy: {acc:.4f}, AUC: {auc:.4f}\nUsage Status: {msg.split(':')[-1].strip()} use(s) left."
|
| 308 |
+
|
| 309 |
+
return full_metrics, ""
|
| 310 |
+
except Exception as e:
|
| 311 |
+
# Failed execution, do not increment count
|
| 312 |
+
return f"Retraining failed. Check if your file has the 'Converted' column (0 or 1). Error: {e}", ""
|
| 313 |
+
|
| 314 |
+
# ----------------------------
|
| 315 |
+
# 5. Gradio Interface
|
| 316 |
+
# ----------------------------
|
| 317 |
|
| 318 |
+
# Instructions for Tooltip
|
| 319 |
+
INSTRUCTION_STEPS = """
|
| 320 |
+
### How to Use the Ultimate Confidence App
|
| 321 |
+
|
| 322 |
+
1. **Activate App:** Enter your Name and Email and click 'Activate App'. This records your usage status in **user\_activations\_SalesPilot.csv**.
|
| 323 |
+
2. **Download Sample (Optional):** Click 'Download Sample CSV' to see the required format for your leads data.
|
| 324 |
+
3. **Upload Data:** Upload your CSV file containing the leads you want to score (must include Name, Industry, Job\_Title, Company\_Size, Lead\_Source).
|
| 325 |
+
4. **Predict:** Click '🔮 Predict Leads'.
|
| 326 |
+
* **Result:** The 'Top 10 Ultimate Confidence Leads' table shows the leads the model is **>95%** sure will convert.
|
| 327 |
+
* **Download:** Use the download button at the bottom to get the full scored list.
|
| 328 |
+
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.
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
with gr.Blocks(title="Ultimate Confidence Lead Scoring") as app:
|
| 332 |
+
|
| 333 |
+
# State variable for managing app activation
|
| 334 |
+
app_active = gr.State(False)
|
| 335 |
+
|
| 336 |
+
gr.Markdown("# 🎯 Ultimate Confidence Lead Targeting")
|
| 337 |
+
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**.")
|
| 338 |
+
|
| 339 |
+
# --- Tooltip Button & Modal ---
|
| 340 |
+
with gr.Row():
|
| 341 |
+
gr.Markdown(f"***IP Usage Tracking: {'Enabled' if IP_LIMIT_ENABLED else 'Disabled'} ({IP_MAX_USES} max uses)***")
|
| 342 |
+
instructions_btn = gr.Button("❓ How to Use App", scale=0)
|
| 343 |
+
|
| 344 |
+
instructions_modal = gr.Modal(
|
| 345 |
+
INSTRUCTION_STEPS,
|
| 346 |
+
visible=False,
|
| 347 |
+
title="App Instructions & Usage",
|
| 348 |
+
show_close_btn=True
|
| 349 |
+
)
|
| 350 |
+
instructions_btn.click(lambda: gr.update(visible=True), outputs=[instructions_modal])
|
| 351 |
+
|
| 352 |
+
# --- Activation Block ---
|
| 353 |
+
with gr.Column(visible=True) as activation_block:
|
| 354 |
+
gr.Markdown("### 🔑 App Activation Required")
|
| 355 |
+
with gr.Row():
|
| 356 |
+
user_name = gr.Textbox(label="Your Name", placeholder="e.g., Jane Doe")
|
| 357 |
+
user_email = gr.Textbox(label="Your Email", placeholder="e.g., jane@company.com")
|
| 358 |
+
|
| 359 |
+
activation_message = gr.Textbox(label="Status", interactive=False)
|
| 360 |
+
activate_btn = gr.Button("🚀 Activate App")
|
| 361 |
+
|
| 362 |
+
# --- Main App Block (Initially Hidden) ---
|
| 363 |
+
with gr.Column(visible=False) as main_app_block:
|
| 364 |
+
|
| 365 |
+
with gr.Row():
|
| 366 |
+
sample_btn = gr.File(label="📥 Download Sample CSV", file_types=[".csv"], value=SAMPLE_FILE)
|
| 367 |
+
|
| 368 |
+
with gr.Row():
|
| 369 |
+
file_input = gr.File(type="filepath", file_types=[".csv"], label="📤 Upload Your Leads CSV")
|
| 370 |
+
predict_btn = gr.Button("🔮 Predict Leads")
|
| 371 |
+
retrain_btn = gr.Button("🔁 Retrain Model Using Uploaded Data")
|
| 372 |
+
|
| 373 |
+
# Outputs
|
| 374 |
+
clean_out = gr.Dataframe(label=f"Top 10 Ultimate Confidence Leads (>= {int(HIGH_PRECISION_THRESHOLD*100)}%)")
|
| 375 |
+
raw_out = gr.Dataframe(label="Raw Predictions (First 10 Rows)")
|
| 376 |
+
summary_out = gr.Dataframe(label="Category Confidence Summary")
|
| 377 |
+
metrics_out = gr.Textbox(label="Model Settings")
|
| 378 |
+
train_metrics = gr.Textbox(label="Retraining Accuracy (Your Data)")
|
| 379 |
+
scored_download = gr.File(label="⬇️ Download Scored Leads CSV (Ultimate Confidence)", file_types=[".csv"])
|
| 380 |
+
|
| 381 |
+
# IP Usage Output (for error/status)
|
| 382 |
+
usage_status_out = gr.Textbox(label="Usage Status Message", interactive=False, visible=False)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
# --- Event Handlers ---
|
| 386 |
+
|
| 387 |
+
# Activation Handler
|
| 388 |
+
activate_btn.click(
|
| 389 |
+
fn=handle_activation,
|
| 390 |
+
inputs=[user_name, user_email],
|
| 391 |
+
outputs=[main_app_block, activation_block, activation_message, app_active],
|
| 392 |
+
# Only process if the app is not already active
|
| 393 |
+
condition=app_active.value == False
|
| 394 |
+
)
|
| 395 |
|
| 396 |
+
# Prediction Handler
|
| 397 |
predict_btn.click(
|
| 398 |
+
fn=wrapper_predict,
|
| 399 |
+
inputs=[file_input, gr.Request()], # Pass gr.Request() for IP tracking
|
| 400 |
+
outputs=[clean_out, raw_out, summary_out, metrics_out, sample_btn, scored_download, usage_status_out]
|
| 401 |
)
|
| 402 |
|
| 403 |
+
# Retraining Handler
|
| 404 |
retrain_btn.click(
|
| 405 |
+
fn=wrapper_retrain,
|
| 406 |
+
inputs=[file_input, gr.Request()], # Pass gr.Request() for IP tracking
|
| 407 |
+
outputs=[train_metrics, usage_status_out]
|
| 408 |
)
|
| 409 |
|
| 410 |
+
# Launch the Gradio app
|
| 411 |
if __name__ == "__main__":
|
| 412 |
+
# app.launch(share=True) # Use this for public sharing
|
| 413 |
+
pass # In this environment, we just define the app
|