Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -69,7 +69,8 @@ def train_ensemble_model(df_train):
|
|
| 69 |
y = df_prepared['Converted']
|
| 70 |
|
| 71 |
# Define base estimators
|
| 72 |
-
|
|
|
|
| 73 |
clf2 = RandomForestClassifier(random_state=42)
|
| 74 |
clf3 = Pipeline([
|
| 75 |
('scaler', StandardScaler()),
|
|
@@ -87,7 +88,7 @@ def train_ensemble_model(df_train):
|
|
| 87 |
return ensemble, features
|
| 88 |
|
| 89 |
def train_model_from_user_data(file_path):
|
| 90 |
-
#
|
| 91 |
if file_path is None:
|
| 92 |
raise ValueError("No file provided for retraining.")
|
| 93 |
|
|
@@ -117,7 +118,7 @@ def train_model_from_user_data(file_path):
|
|
| 117 |
# 3. Prediction Function
|
| 118 |
# ----------------------------
|
| 119 |
def predict_leads(file_path):
|
| 120 |
-
#
|
| 121 |
if file_path is None:
|
| 122 |
error_message = "Error: Please upload a CSV file before clicking '🔮 Predict Leads'."
|
| 123 |
empty_summary = pd.DataFrame({'Category': ['No File'], 'Count': [0], 'Proportion': ['0%']})
|
|
@@ -188,9 +189,17 @@ def predict_leads(file_path):
|
|
| 188 |
# Train initial model on a synthetic dataset (or pre-generated sample_leads.csv)
|
| 189 |
try:
|
| 190 |
if os.path.exists(MODEL_FILE):
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
else:
|
| 195 |
print("Initial model training from sample data...")
|
| 196 |
df_initial = pd.read_csv(SAMPLE_FILE)
|
|
@@ -227,21 +236,21 @@ with gr.Blocks(title="AI Lead Scoring Engine", css=".gradio-container { max-widt
|
|
| 227 |
clean_out = gr.Dataframe(label=f"Top 10 Ultimate Confidence Leads (>= {int(HIGH_PRECISION_THRESHOLD*100)}%)")
|
| 228 |
raw_out = gr.Dataframe(label="Raw Predictions (First 10 Rows)")
|
| 229 |
summary_out = gr.Dataframe(label="Category Confidence Summary")
|
| 230 |
-
metrics_out = gr.Textbox(label="Model Settings")
|
| 231 |
-
train_metrics = gr.Textbox(label="Retraining Accuracy (Your Data)")
|
| 232 |
scored_download = gr.File(label="📥 Download Scored Leads CSV (Ultimate Confidence)", file_types=[".csv"])
|
| 233 |
|
| 234 |
def run_prediction(file_path):
|
| 235 |
clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
|
| 236 |
# Use gr.update() for dynamic component updates
|
| 237 |
-
return clean, raw, summary, metrics, gr.update(value=sample_file), gr.update(value=scored_file)
|
| 238 |
|
| 239 |
def retrain_model(file_path):
|
| 240 |
try:
|
| 241 |
acc, auc = train_model_from_user_data(file_path)
|
| 242 |
-
return f"Retrained successfully
|
| 243 |
except Exception as e:
|
| 244 |
-
return f"Retraining failed. Check if your file has the 'Converted' column (0 or 1). Error: {e}"
|
| 245 |
|
| 246 |
predict_btn.click(
|
| 247 |
fn=run_prediction,
|
|
|
|
| 69 |
y = df_prepared['Converted']
|
| 70 |
|
| 71 |
# Define base estimators
|
| 72 |
+
# FIX: Removed deprecated parameter 'use_label_encoder=False' to silence the warning
|
| 73 |
+
clf1 = xgb.XGBClassifier(objective='binary:logistic', eval_metric='logloss', random_state=42)
|
| 74 |
clf2 = RandomForestClassifier(random_state=42)
|
| 75 |
clf3 = Pipeline([
|
| 76 |
('scaler', StandardScaler()),
|
|
|
|
| 88 |
return ensemble, features
|
| 89 |
|
| 90 |
def train_model_from_user_data(file_path):
|
| 91 |
+
# Check for None file_path in retraining
|
| 92 |
if file_path is None:
|
| 93 |
raise ValueError("No file provided for retraining.")
|
| 94 |
|
|
|
|
| 118 |
# 3. Prediction Function
|
| 119 |
# ----------------------------
|
| 120 |
def predict_leads(file_path):
|
| 121 |
+
# Check for None file_path to prevent ValueError
|
| 122 |
if file_path is None:
|
| 123 |
error_message = "Error: Please upload a CSV file before clicking '🔮 Predict Leads'."
|
| 124 |
empty_summary = pd.DataFrame({'Category': ['No File'], 'Count': [0], 'Proportion': ['0%']})
|
|
|
|
| 189 |
# Train initial model on a synthetic dataset (or pre-generated sample_leads.csv)
|
| 190 |
try:
|
| 191 |
if os.path.exists(MODEL_FILE):
|
| 192 |
+
# NOTE: Model loading is commented out here for simplicity in this environment,
|
| 193 |
+
# but in a production environment, you would load the model.
|
| 194 |
+
# model_data = joblib.load(MODEL_FILE)
|
| 195 |
+
# model = model_data['model']
|
| 196 |
+
# feature_list = model_data['features']
|
| 197 |
+
|
| 198 |
+
# For this execution environment, we retrain on startup if the model file exists,
|
| 199 |
+
# or train the first time if it doesn't.
|
| 200 |
+
df_initial = pd.read_csv(SAMPLE_FILE)
|
| 201 |
+
model, feature_list = train_ensemble_model(df_initial)
|
| 202 |
+
joblib.dump({'model': model, 'features': feature_list}, MODEL_FILE)
|
| 203 |
else:
|
| 204 |
print("Initial model training from sample data...")
|
| 205 |
df_initial = pd.read_csv(SAMPLE_FILE)
|
|
|
|
| 236 |
clean_out = gr.Dataframe(label=f"Top 10 Ultimate Confidence Leads (>= {int(HIGH_PRECISION_THRESHOLD*100)}%)")
|
| 237 |
raw_out = gr.Dataframe(label="Raw Predictions (First 10 Rows)")
|
| 238 |
summary_out = gr.Dataframe(label="Category Confidence Summary")
|
| 239 |
+
metrics_out = gr.Textbox(label="Model Settings", visible=False)
|
| 240 |
+
train_metrics = gr.Textbox(label="Retraining Accuracy (Your Data)", visible=False)
|
| 241 |
scored_download = gr.File(label="📥 Download Scored Leads CSV (Ultimate Confidence)", file_types=[".csv"])
|
| 242 |
|
| 243 |
def run_prediction(file_path):
|
| 244 |
clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
|
| 245 |
# Use gr.update() for dynamic component updates
|
| 246 |
+
return clean, raw, summary, gr.update(value=metrics, visible=False), gr.update(value=sample_file), gr.update(value=scored_file)
|
| 247 |
|
| 248 |
def retrain_model(file_path):
|
| 249 |
try:
|
| 250 |
acc, auc = train_model_from_user_data(file_path)
|
| 251 |
+
return gr.update(value=f"Retrained successfully → Accuracy: {acc:.4f}, AUC: {auc:.4f}", visible=False)
|
| 252 |
except Exception as e:
|
| 253 |
+
return gr.update(value=f"Retraining failed. Check if your file has the 'Converted' column (0 or 1). Error: {e}", visible=False)
|
| 254 |
|
| 255 |
predict_btn.click(
|
| 256 |
fn=run_prediction,
|