abhidgp1978 commited on
Commit
ce70852
·
verified ·
1 Parent(s): b930671

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -25
app.py CHANGED
@@ -13,7 +13,7 @@ SAMPLE_FILE = "sample_leads.csv"
13
  # ----------------------------
14
  # 1. Generate Sample Data (for download)
15
  # ----------------------------
16
- def generate_sample_data(n=10):
17
  industries = ["Healthcare", "Finance", "Tech", "Education", "Retail"]
18
  job_titles = ["Intern", "Manager", "Director", "VP", "C-Level"]
19
  lead_sources = ["Web", "Email", "Referral", "Ad", "Event"]
@@ -24,18 +24,20 @@ def generate_sample_data(n=10):
24
  "Job_Title": np.random.choice(job_titles, n),
25
  "Company_Size": np.random.randint(10, 5000, n),
26
  "Lead_Source": np.random.choice(lead_sources, n),
 
 
27
  }
28
  df = pd.DataFrame(data)
29
  return df
30
 
31
- # Pre-generate sample CSV if not exists
32
  if not os.path.exists(SAMPLE_FILE):
33
- generate_sample_data(10).to_csv(SAMPLE_FILE, index=False)
34
 
35
  # ----------------------------
36
- # 2. Train XGBoost Model (if not exists)
37
  # ----------------------------
38
- def generate_training_data(n=500):
39
  industries = ["Healthcare", "Finance", "Tech", "Education", "Retail"]
40
  job_titles = ["Intern", "Manager", "Director", "VP", "C-Level"]
41
  lead_sources = ["Web", "Email", "Referral", "Ad", "Event"]
@@ -65,23 +67,52 @@ def train_model():
65
  dtrain = xgb.DMatrix(X_train, label=y_train)
66
  dtest = xgb.DMatrix(X_test, label=y_test)
67
 
68
- params = {"objective": "binary:logistic", "eval_metric": "logloss", "max_depth": 4, "eta": 0.1}
69
- model = xgb.train(params, dtrain, num_boost_round=100)
70
  preds = (model.predict(dtest) > 0.5).astype(int)
71
  acc = accuracy_score(y_test, preds)
72
 
73
  joblib.dump(model, MODEL_FILE)
74
  return acc
75
 
 
76
  if not os.path.exists(MODEL_FILE):
77
  acc = train_model()
78
- print(f"Trained new XGBoost model, accuracy={acc:.2f}")
79
 
80
- model = joblib.load(MODEL_FILE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  # ----------------------------
83
- # 3. Classification Function
84
  # ----------------------------
 
 
85
  def classify(prob):
86
  if prob >= 0.7:
87
  return "Most Likely"
@@ -91,31 +122,26 @@ def classify(prob):
91
  return "Not Preferred"
92
 
93
  # ----------------------------
94
- # 4. Predict Leads Function
95
  # ----------------------------
96
  def predict_leads(file_path):
97
  df = pd.read_csv(file_path)
98
  features = df.drop(columns=[c for c in ["Converted", "Name"] if c in df.columns])
99
  features_encoded = pd.get_dummies(features, dummy_na=True)
100
-
101
  dmatrix = xgb.DMatrix(features_encoded.reindex(columns=model.feature_names, fill_value=0))
102
  probs = model.predict(dmatrix)
103
 
104
  df["AI_Probability"] = probs
105
  df["AI_Category"] = df["AI_Probability"].apply(classify)
106
 
107
- # Clean view
108
  clean_view = df[["Name", "Industry", "Job_Title", "AI_Category"]]
109
-
110
- # Category confidence summary
111
  summary = df.groupby("AI_Category")["AI_Probability"].agg(["count", "mean"]).reset_index()
112
  summary.rename(columns={"mean": "Avg_Probability", "count": "Num_Leads"}, inplace=True)
113
 
114
- # Estimated Accuracy / AUC if Converted exists
115
  metrics_text = ""
116
  if "Converted" in df.columns:
117
  y_true = df["Converted"]
118
- y_pred = df["AI_Category"].map({"Most Likely":1, "Likely":1, "Not Preferred":0})
119
  accuracy = accuracy_score(y_true, y_pred)
120
  try:
121
  auc = roc_auc_score(y_true, df["AI_Probability"])
@@ -125,41 +151,52 @@ def predict_leads(file_path):
125
  if auc:
126
  metrics_text += f"AUC: {auc:.2f}"
127
 
128
- # Save scored leads for download
129
  scored_file = "scored_leads.csv"
130
  df.to_csv(scored_file, index=False)
131
 
132
  return clean_view, df, summary, metrics_text, SAMPLE_FILE, scored_file
133
 
134
  # ----------------------------
135
- # 5. Gradio App
136
  # ----------------------------
137
  with gr.Blocks() as demo:
138
- gr.Markdown("# AI Lead Scoring App")
139
- gr.Markdown("Upload your leads CSV and get predictions, confidence, and accuracy metrics.")
140
 
141
  with gr.Row():
142
- sample_btn = gr.File(label="Download Sample CSV", file_types=[".csv"], value=SAMPLE_FILE)
143
 
144
  with gr.Row():
145
- file_input = gr.File(type="filepath", file_types=[".csv"], label="Upload Your Leads CSV")
146
- predict_btn = gr.Button("Predict Leads")
147
- scored_download = gr.File(label="Download Scored Leads CSV", file_types=[".csv"])
148
 
149
  clean_out = gr.Dataframe(label="Predicted Leads")
150
  raw_out = gr.Dataframe(label="Raw Predictions")
151
  summary_out = gr.Dataframe(label="Category Confidence Summary")
152
  metrics_out = gr.Textbox(label="Estimated Accuracy / AUC")
 
 
153
 
154
  def run_prediction(file_path):
155
  clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
156
  return clean, raw, summary, metrics, sample_file, scored_file
157
 
 
 
 
 
158
  predict_btn.click(
159
  fn=run_prediction,
160
  inputs=[file_input],
161
  outputs=[clean_out, raw_out, summary_out, metrics_out, sample_btn, scored_download]
162
  )
163
 
 
 
 
 
 
 
164
  if __name__ == "__main__":
165
  demo.launch()
 
13
  # ----------------------------
14
  # 1. Generate Sample Data (for download)
15
  # ----------------------------
16
+ def generate_sample_data(n=150):
17
  industries = ["Healthcare", "Finance", "Tech", "Education", "Retail"]
18
  job_titles = ["Intern", "Manager", "Director", "VP", "C-Level"]
19
  lead_sources = ["Web", "Email", "Referral", "Ad", "Event"]
 
24
  "Job_Title": np.random.choice(job_titles, n),
25
  "Company_Size": np.random.randint(10, 5000, n),
26
  "Lead_Source": np.random.choice(lead_sources, n),
27
+ # Optional column for labeling real leads later
28
+ "Converted": np.random.choice([0, 1], n, p=[0.8, 0.2])
29
  }
30
  df = pd.DataFrame(data)
31
  return df
32
 
33
+ # Pre-generate sample file
34
  if not os.path.exists(SAMPLE_FILE):
35
+ generate_sample_data(150).to_csv(SAMPLE_FILE, index=False)
36
 
37
  # ----------------------------
38
+ # 2. Default Model Training (synthetic)
39
  # ----------------------------
40
+ def generate_training_data(n=1000):
41
  industries = ["Healthcare", "Finance", "Tech", "Education", "Retail"]
42
  job_titles = ["Intern", "Manager", "Director", "VP", "C-Level"]
43
  lead_sources = ["Web", "Email", "Referral", "Ad", "Event"]
 
67
  dtrain = xgb.DMatrix(X_train, label=y_train)
68
  dtest = xgb.DMatrix(X_test, label=y_test)
69
 
70
+ params = {"objective": "binary:logistic", "eval_metric": "logloss", "max_depth": 5, "eta": 0.15}
71
+ model = xgb.train(params, dtrain, num_boost_round=150)
72
  preds = (model.predict(dtest) > 0.5).astype(int)
73
  acc = accuracy_score(y_test, preds)
74
 
75
  joblib.dump(model, MODEL_FILE)
76
  return acc
77
 
78
+ # Train synthetic model if not exists
79
  if not os.path.exists(MODEL_FILE):
80
  acc = train_model()
81
+ print(f"Trained default XGBoost model, accuracy={acc:.2f}")
82
 
83
+ # ----------------------------
84
+ # 3. Retrain from User Data
85
+ # ----------------------------
86
+ def train_model_from_user_data(csv_path):
87
+ """Train model using manually labeled lead data (Converted column required)."""
88
+ df = pd.read_csv(csv_path)
89
+
90
+ if "Converted" not in df.columns:
91
+ raise ValueError("Your CSV must include a 'Converted' column (1=Most Likely, 0=Others).")
92
+
93
+ X = pd.get_dummies(df.drop(columns=["Converted", "Name"]), dummy_na=True)
94
+ y = df["Converted"]
95
+
96
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
97
+ dtrain = xgb.DMatrix(X_train, label=y_train)
98
+ dtest = xgb.DMatrix(X_test, label=y_test)
99
+
100
+ params = {"objective": "binary:logistic", "eval_metric": "logloss", "max_depth": 5, "eta": 0.1}
101
+ model = xgb.train(params, dtrain, num_boost_round=200)
102
+
103
+ preds = (model.predict(dtest) > 0.5).astype(int)
104
+ acc = accuracy_score(y_test, preds)
105
+ auc = roc_auc_score(y_test, model.predict(dtest))
106
+
107
+ joblib.dump(model, MODEL_FILE)
108
+ print(f"✅ Model retrained from user data | Accuracy: {acc:.2f} | AUC: {auc:.2f}")
109
+ return acc, auc
110
 
111
  # ----------------------------
112
+ # 4. Load model for prediction
113
  # ----------------------------
114
+ model = joblib.load(MODEL_FILE)
115
+
116
  def classify(prob):
117
  if prob >= 0.7:
118
  return "Most Likely"
 
122
  return "Not Preferred"
123
 
124
  # ----------------------------
125
+ # 5. Prediction Function
126
  # ----------------------------
127
  def predict_leads(file_path):
128
  df = pd.read_csv(file_path)
129
  features = df.drop(columns=[c for c in ["Converted", "Name"] if c in df.columns])
130
  features_encoded = pd.get_dummies(features, dummy_na=True)
 
131
  dmatrix = xgb.DMatrix(features_encoded.reindex(columns=model.feature_names, fill_value=0))
132
  probs = model.predict(dmatrix)
133
 
134
  df["AI_Probability"] = probs
135
  df["AI_Category"] = df["AI_Probability"].apply(classify)
136
 
 
137
  clean_view = df[["Name", "Industry", "Job_Title", "AI_Category"]]
 
 
138
  summary = df.groupby("AI_Category")["AI_Probability"].agg(["count", "mean"]).reset_index()
139
  summary.rename(columns={"mean": "Avg_Probability", "count": "Num_Leads"}, inplace=True)
140
 
 
141
  metrics_text = ""
142
  if "Converted" in df.columns:
143
  y_true = df["Converted"]
144
+ y_pred = df["AI_Category"].map({"Most Likely": 1, "Likely": 1, "Not Preferred": 0})
145
  accuracy = accuracy_score(y_true, y_pred)
146
  try:
147
  auc = roc_auc_score(y_true, df["AI_Probability"])
 
151
  if auc:
152
  metrics_text += f"AUC: {auc:.2f}"
153
 
 
154
  scored_file = "scored_leads.csv"
155
  df.to_csv(scored_file, index=False)
156
 
157
  return clean_view, df, summary, metrics_text, SAMPLE_FILE, scored_file
158
 
159
  # ----------------------------
160
+ # 6. Gradio App UI
161
  # ----------------------------
162
  with gr.Blocks() as demo:
163
+ gr.Markdown("# 🧠 AI Lead Scoring App")
164
+ gr.Markdown("Upload your leads CSV to get predictions and optionally retrain the AI using your manually marked data.")
165
 
166
  with gr.Row():
167
+ sample_btn = gr.File(label="📥 Download Sample CSV", file_types=[".csv"], value=SAMPLE_FILE)
168
 
169
  with gr.Row():
170
+ file_input = gr.File(type="filepath", file_types=[".csv"], label="📤 Upload Your Leads CSV")
171
+ predict_btn = gr.Button("🔮 Predict Leads")
172
+ retrain_btn = gr.Button("🔁 Retrain Model Using Uploaded Data")
173
 
174
  clean_out = gr.Dataframe(label="Predicted Leads")
175
  raw_out = gr.Dataframe(label="Raw Predictions")
176
  summary_out = gr.Dataframe(label="Category Confidence Summary")
177
  metrics_out = gr.Textbox(label="Estimated Accuracy / AUC")
178
+ train_metrics = gr.Textbox(label="Retraining Accuracy (Your Data)")
179
+ scored_download = gr.File(label="📥 Download Scored Leads CSV", file_types=[".csv"])
180
 
181
  def run_prediction(file_path):
182
  clean, raw, summary, metrics, sample_file, scored_file = predict_leads(file_path)
183
  return clean, raw, summary, metrics, sample_file, scored_file
184
 
185
+ def retrain_model(file_path):
186
+ acc, auc = train_model_from_user_data(file_path)
187
+ return f"Retrained successfully → Accuracy: {acc:.2f}, AUC: {auc:.2f}"
188
+
189
  predict_btn.click(
190
  fn=run_prediction,
191
  inputs=[file_input],
192
  outputs=[clean_out, raw_out, summary_out, metrics_out, sample_btn, scored_download]
193
  )
194
 
195
+ retrain_btn.click(
196
+ fn=retrain_model,
197
+ inputs=[file_input],
198
+ outputs=[train_metrics]
199
+ )
200
+
201
  if __name__ == "__main__":
202
  demo.launch()