MBG0903 commited on
Commit
5f7d6cd
·
verified ·
1 Parent(s): e306ed9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1430 -204
app.py CHANGED
@@ -15,18 +15,41 @@ from services.lead_logic import (
15
  qualify_from_conversation,
16
  generate_owner_summary,
17
  )
 
18
  from services.voice_service import VoiceService
19
 
 
20
  APP_TITLE = "AI Lead Conversion Prototype | Interior Business"
 
21
  DATA_DIR = Path("data")
22
  DATA_DIR.mkdir(exist_ok=True)
 
23
  VOICE = VoiceService()
24
 
25
- STAFF = ["Employee 1", "Employee 2", "Employee 3", "Employee 4"]
 
 
 
 
 
 
26
 
 
 
 
27
 
28
  def empty_attendance():
29
- return pd.DataFrame({"Employee": STAFF, "Attendance": ["Present", "Present", "Present", "Present"]})
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def load_initial_leads():
@@ -36,16 +59,70 @@ def load_initial_leads():
36
  def kpis(df: pd.DataFrame):
37
  if df is None or df.empty:
38
  return 0, 0, 0, 0, 0
 
39
  total = len(df)
40
- hot = int((df.get("Priority", pd.Series(dtype=str)) == "HOT").sum())
41
- qualified = int(df.get("Status", pd.Series(dtype=str)).isin(["Qualified", "Site Visit Requested", "Quote Requested"]).sum())
42
- followups = int(df.get("Next Action", pd.Series(dtype=str)).astype(str).str.contains("follow|retry|callback", case=False, na=False).sum())
43
- human = int(df.get("Human Intervention", pd.Series(dtype=str)).astype(str).str.lower().isin(["yes", "true"]).sum())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  return total, hot, qualified, followups, human
45
 
46
 
47
  def refresh_dashboard(df):
48
  total, hot, qualified, followups, human = kpis(df)
 
49
  return (
50
  f"### {total}\nTotal Leads",
51
  f"### {hot}\n🔥 Hot Leads",
@@ -56,81 +133,261 @@ def refresh_dashboard(df):
56
  )
57
 
58
 
 
 
 
 
59
  def upload_excel(file_obj):
60
  if not file_obj:
61
  df = build_demo_leads()
62
- return df, "No file selected. Demo data loaded.", gr.update(choices=df["Lead ID"].tolist(), value=df.iloc[0]["Lead ID"])
 
 
 
 
 
 
 
 
 
63
  try:
64
  df = normalize_excel(file_obj)
65
- msg = f"Loaded {len(df)} leads from Excel and mapped the sheet into the prototype lead model."
 
 
 
 
 
66
  first = df.iloc[0]["Lead ID"] if len(df) else None
67
- return df, msg, gr.update(choices=df["Lead ID"].tolist(), value=first)
 
 
 
 
 
 
 
 
 
68
  except Exception as e:
69
  df = build_demo_leads()
70
- return df, f"Could not map that workbook automatically: {e}. Demo data loaded instead.", gr.update(choices=df["Lead ID"].tolist(), value=df.iloc[0]["Lead ID"])
 
 
 
 
 
 
 
 
 
71
 
72
 
 
 
 
 
73
  def allocate(df, attendance, ai_first):
74
  if df is None or df.empty:
75
  return df, "No leads available."
76
- present = attendance.loc[attendance["Attendance"].astype(str).str.lower() == "present", "Employee"].tolist()
77
- result = assign_leads(df.copy(), present, ai_first=ai_first)
78
- mode = "AI-first qualification" if ai_first else "human round-robin"
79
- return result, f"Allocation completed using {mode}. Present staff: {', '.join(present) if present else 'None'}."
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  def get_lead(df, lead_id):
83
  if df is None or df.empty or not lead_id:
84
  return None
85
- row = df[df["Lead ID"].astype(str) == str(lead_id)]
 
 
 
 
 
86
  if row.empty:
87
  return None
 
88
  return row.iloc[0].to_dict()
89
 
90
 
91
  def lead_card(df, lead_id):
92
  lead = get_lead(df, lead_id)
 
93
  if not lead:
94
  return "Select a lead."
 
95
  return f"""
96
- ### {lead.get('Customer Name','Customer')} — {lead.get('Lead ID','')}
97
- **Phone:** {lead.get('Phone','')}
98
- **Location:** {lead.get('Location','')}
99
- **Requirement:** {lead.get('Requirement','')}
100
- **Current Status:** {lead.get('Status','New')}
101
- **Assigned To:** {lead.get('Assigned To','AI Queue')}
102
- **Priority:** {lead.get('Priority','Unscored')}
 
 
103
  """
104
 
105
 
106
- def demo_script(df, lead_id, language, scenario):
 
 
 
 
 
 
 
 
 
107
  lead = get_lead(df, lead_id)
 
108
  if not lead:
109
  return "Select a lead first."
110
- name = lead.get("Customer Name") or "there"
111
- requirement = lead.get("Requirement") or "interior requirement"
 
 
 
 
 
 
 
 
 
112
  intro = {
113
- "English": f"Hello {name}. I’m the automated assistant from the interior design team. You recently submitted an enquiry regarding {requirement}. Is this a good time for a quick 2-minute discussion?",
114
- "Kannada + English": f"Hello {name}. Naanu interior design team-na automated assistant. Neevu recently {requirement} bagge enquiry submit maadidri. Iga 2 minutes maatadakke convenient-aa?",
115
- "Hindi + English": f"Hello {name}. Main interior design team ka automated assistant hoon. Aapne recently {requirement} ke liye enquiry submit ki thi. Kya abhi 2 minute baat karna convenient hai?",
116
- }.get(language, "Hello. I’m the automated assistant from the interior design team.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  prompts = {
118
- "Full qualification": "I’ll understand your property, location, timeline, approximate budget, whether you have a floor plan, and whether you would like a catalogue, quotation or site visit.",
119
- "Site visit interest": "I’ll quickly confirm your property details and whether you would like our team to arrange a site visit.",
120
- "Catalogue request": "I’ll understand your requirement and can arrange for our catalogue and previous work references to be sent.",
121
- "No answer / callback": "This scenario demonstrates a missed call or callback request and automatic scheduling.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  }
123
- return intro + "\n\n" + prompts.get(scenario, prompts["Full qualification"])
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- def simulate_call(df, lead_id, phone_override, language, scenario, customer_reply):
127
- lead = get_lead(df, lead_id)
128
  if not lead:
129
- return df, "No lead selected.", "", "", "", gr.update()
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
- phone = (phone_override or lead.get("Phone") or "").strip()
132
  if not phone:
133
- return df, "Enter a controlled test phone number.", "", "", "", gr.update()
 
 
 
 
 
 
 
134
 
135
  call_result = VOICE.start_call(
136
  phone=phone,
@@ -140,17 +397,38 @@ def simulate_call(df, lead_id, phone_override, language, scenario, customer_repl
140
  customer_reply=customer_reply,
141
  )
142
 
143
- qualification = qualify_from_conversation(lead, call_result["transcript"], scenario=scenario)
 
 
 
 
 
144
  out = df.copy()
145
- idx = out.index[out["Lead ID"].astype(str) == str(lead_id)][0]
 
 
 
 
 
146
  for key, value in qualification.items():
147
  if key in out.columns:
148
  out.at[idx, key] = value
149
- out.at[idx, "Last Contact"] = datetime.now().strftime("%Y-%m-%d %H:%M")
150
- out.at[idx, "Call Result"] = call_result["result"]
 
 
 
 
 
 
 
 
 
 
151
 
152
  result_md = f"""
153
  ### ✅ AI Qualification Completed
 
154
  **Call mode:** {call_result['mode']}
155
  **Outcome:** {call_result['result']}
156
  **Status:** {qualification['Status']}
@@ -159,66 +437,287 @@ def simulate_call(df, lead_id, phone_override, language, scenario, customer_repl
159
  **Next Action:** {qualification['Next Action']}
160
  **Human Intervention:** {qualification['Human Intervention']}
161
  """
 
162
  summary = qualification["AI Summary"]
163
- wa = qualification.get("WhatsApp Action", "No WhatsApp action required")
164
- choices = out["Lead ID"].tolist()
165
- return out, result_md, call_result["transcript"], summary, wa, gr.update(choices=choices, value=lead_id)
166
 
 
 
 
 
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
- def whatsapp_lead_update(df, lead_id, history, customer_message):
170
- """Simulate a WhatsApp Business conversation while using the same lead engine."""
171
- lead = get_lead(df, lead_id)
172
  history = history or []
173
- message = (customer_message or "").strip()
 
 
 
 
 
174
  if not lead:
175
- return df, history, "", "Select a lead first.", gr.update()
 
 
 
 
 
 
 
176
  if not message:
177
- return df, history, "", "Type a customer message.", gr.update()
 
 
 
 
 
 
178
 
179
  previous_customer_text = " ".join(
180
- str(item.get("content", "")) for item in history
181
- if isinstance(item, dict) and item.get("role") == "user"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  )
183
- customer_context = (previous_customer_text + " " + message).strip()
184
- qualification = qualify_from_conversation(lead, customer_context, scenario="Full qualification")
185
 
186
  lower = message.lower()
187
- name = lead.get("Customer Name") or "there"
188
-
189
- if any(x in lower for x in ["not interested", "no requirement", "don't need", "do not need"]):
190
- reply = f"Understood, {name}. I’ll close this enquiry for now. Thank you for your time."
191
- elif any(x in lower for x in ["site visit", "visit my", "visit the site", "come and visit", "someone to visit"]):
192
- reply = "Certainly. I’ve marked this as a site-visit request. Our human coordinator will confirm the available date and time with you."
193
- elif any(x in lower for x in ["quotation", "quote", "estimate"]):
194
- reply = "Sure. I’ve recorded your quotation request. I’ll collect the required details and route this to our team for review before the quotation is shared."
195
- elif any(x in lower for x in ["catalog", "catalogue", "portfolio", "previous work", "images", "photos", "designs"]):
196
- reply = "Absolutely. I’ve noted that you would like our catalogue / previous-work references. In production, the approved material would be sent here automatically."
197
- elif any(x in lower for x in ["floor plan", "floorplan"]):
198
- reply = "Great. Please share the floor plan here when convenient. The production WhatsApp integration can attach it directly to your lead record for the design team."
199
- elif re.search(r"\b\d+(?:\.\d+)?\s*(?:lakh|lac|lakhs|lacs)\b", lower):
200
- reply = "Thank you. I’ve captured your approximate budget. Could you also tell me your property type and when you would like the interior work to begin?"
201
- elif any(x in lower for x in ["3bhk", "3 bhk", "2bhk", "2 bhk", "1bhk", "1 bhk", "villa", "apartment", "house"]):
202
- reply = "Thanks, I’ve captured the property details. Do you have an approximate budget, expected timeline, or floor plan available?"
203
- elif any(x in lower for x in ["hello", "hi", "hey"]):
204
- reply = f"Hello {name}! I’m the AI assistant for the interior design team. I can help with your requirement, catalogue, floor plan, quotation, follow-up, or site-visit request. How can I help?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  else:
206
- reply = "Thanks for the information. I’ve added it to your enquiry. Could you share your property type, approximate budget, expected timeline, or whether you need a catalogue, quotation, or site visit?"
 
 
 
 
 
 
207
 
208
  out = df.copy()
209
- idx = out.index[out["Lead ID"].astype(str) == str(lead_id)][0]
 
 
 
 
 
210
  for key, value in qualification.items():
211
  if key in out.columns:
212
- out.at[idx, key] = value
213
- out.at[idx, "Last Contact"] = datetime.now().strftime("%Y-%m-%d %H:%M")
214
- out.at[idx, "Call Result"] = "WhatsApp prototype interaction"
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
  new_history = history + [
217
- {"role": "user", "content": message},
218
- {"role": "assistant", "content": reply},
 
 
 
 
 
 
219
  ]
 
220
  action_md = f"""
221
  ### AI Action
 
222
  **Detected Status:** {qualification['Status']}
223
  **Priority:** {qualification['Priority']}
224
  **Lead Score:** {qualification['Lead Score']}/100
@@ -228,212 +727,939 @@ def whatsapp_lead_update(df, lead_id, history, customer_message):
228
  **Production channel:** WhatsApp Business API
229
  **Prototype channel:** HF chat simulator
230
  """
231
- return out, new_history, "", action_md, gr.update(choices=out["Lead ID"].tolist(), value=lead_id)
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
 
234
- def reset_whatsapp_chat(df, lead_id):
235
- lead = get_lead(df, lead_id)
 
 
 
 
 
 
 
236
  if not lead:
237
- return [], "Select a lead first."
238
- name = lead.get("Customer Name") or "there"
239
- req = lead.get("Requirement") or "your interior requirement"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  opening = (
241
- f"Hello {name}! I’m the AI assistant for the interior design team. "
 
242
  f"I’m following up on your enquiry about {req}. "
243
- "I can help with requirements, catalogue, floor plan, quotation, follow-up, or a site visit. How can I help?"
 
 
 
 
 
 
 
 
 
 
 
 
244
  )
245
- return [{"role": "assistant", "content": opening}], "Conversation reset. Lead data is unchanged."
246
 
247
 
 
 
 
 
248
  def human_queue(df):
249
  if df is None or df.empty:
250
  return pd.DataFrame()
251
- mask = df["Human Intervention"].astype(str).str.lower().isin(["yes", "true"])
252
- cols = ["Lead ID", "Customer Name", "Phone", "Location", "Requirement", "Status", "Priority", "Lead Score", "Next Action", "AI Summary"]
253
- return df.loc[mask, [c for c in cols if c in df.columns]].sort_values(["Lead Score"], ascending=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
 
 
 
 
 
256
  def owner_report(df):
257
  return generate_owner_summary(df)
258
 
259
 
 
 
 
 
260
  CSS = """
261
- .gradio-container {max-width: 1500px !important;}
262
- .kpi {border:1px solid #d9e1ea; border-radius:14px; padding:14px; min-height:95px; background:white;}
263
- .hero {background: linear-gradient(135deg,#0F2C59,#1F4C88); color:white; padding:22px; border-radius:18px; margin-bottom:12px;}
264
- .small-note {font-size:12px; opacity:.8;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  """
266
 
267
- with gr.Blocks(title=APP_TITLE, css=CSS, theme=gr.themes.Soft()) as demo:
268
- leads_state = gr.State(load_initial_leads())
269
 
270
- gr.HTML("""
271
- <div class='hero'>
272
- <h1 style='margin:0'>AI Lead Conversion Prototype</h1>
273
- <p style='margin:7px 0 0'>Interior Business • Meta Lead → AI Qualification → Status → WhatsApp Action → Human Handoff</p>
274
- </div>
275
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
 
277
- with gr.Tab("🏠 Dashboard"):
278
  with gr.Row():
279
- k1 = gr.Markdown(elem_classes="kpi")
280
- k2 = gr.Markdown(elem_classes="kpi")
281
- k3 = gr.Markdown(elem_classes="kpi")
282
- k4 = gr.Markdown(elem_classes="kpi")
283
- k5 = gr.Markdown(elem_classes="kpi")
284
- dashboard_table = gr.Dataframe(interactive=False, wrap=True, label="Lead Pipeline")
285
- refresh_btn = gr.Button("Refresh Dashboard", variant="primary")
286
-
287
- with gr.Tab("📥 Lead Import"):
288
- gr.Markdown("Upload the client's Excel sheet. The prototype maps common columns such as name, contact, location, requirements, follow-up and remarks into a cleaner lead model.")
289
- excel_file = gr.File(label="Upload Excel (.xlsx/.xls)", file_types=[".xlsx", ".xls"], type="filepath")
290
- import_btn = gr.Button("Load Leads", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  import_msg = gr.Markdown()
292
- imported_table = gr.Dataframe(interactive=False, wrap=True)
293
 
294
- with gr.Tab("👥 Attendance & Allocation"):
295
- gr.Markdown("Mark attendance first. In AI-first mode, new leads go to the AI qualification queue instead of being distributed to all four callers.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  attendance = gr.Dataframe(
297
  value=empty_attendance(),
298
- headers=["Employee", "Attendance"],
299
- datatype=["str", "str"],
 
 
 
 
 
 
300
  interactive=True,
301
  label="Today's Attendance",
302
  )
303
- ai_first = gr.Checkbox(value=True, label="AI-first qualification mode")
304
- allocate_btn = gr.Button("Allocate Today's Leads", variant="primary")
 
 
 
 
 
 
 
 
 
305
  allocation_msg = gr.Markdown()
306
- allocation_table = gr.Dataframe(interactive=False, wrap=True)
307
 
308
- with gr.Tab("📞 AI Calling Agent"):
309
- gr.Markdown("For this first HF version, the conversation and call outcome are simulated safely. The voice-service adapter is already separated so we can plug in a real telephony provider next.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  with gr.Row():
311
- lead_selector = gr.Dropdown(choices=load_initial_leads()["Lead ID"].tolist(), value=load_initial_leads().iloc[0]["Lead ID"], label="Lead")
312
- phone_override = gr.Textbox(label="Controlled Test Phone Number", placeholder="Enter your business number for the later live-call integration")
313
- language = gr.Dropdown(["English", "Kannada + English", "Hindi + English"], value="English", label="Conversation Language")
314
- scenario = gr.Dropdown(["Full qualification", "Site visit interest", "Catalogue request", "No answer / callback"], value="Full qualification", label="Demo Scenario")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  selected_card = gr.Markdown()
316
- generate_script_btn = gr.Button("Generate AI Opening")
317
- ai_opening = gr.Textbox(label="AI Opening / Conversation Goal", lines=5)
 
 
 
 
 
 
 
 
318
  customer_reply = gr.Textbox(
319
- label="Your Demo Reply (act as the customer)",
 
 
 
320
  lines=7,
321
- value="Yes, I have a 3BHK apartment in Banashankari. Possession is next month. My budget is around 12 lakh. I have the floor plan. Please send me your catalogue and I would also like someone to visit the site.",
 
 
 
 
 
 
 
322
  )
323
- call_btn = gr.Button("🤖 Run AI Qualification Call", variant="primary")
 
 
 
 
 
324
  call_result_md = gr.Markdown()
 
325
  with gr.Row():
326
- transcript = gr.Textbox(label="Call Transcript", lines=12)
327
- ai_summary = gr.Textbox(label="AI Call Summary", lines=12)
328
- whatsapp_action = gr.Textbox(label="Automatic WhatsApp / Workflow Action", lines=4)
329
 
330
- with gr.Tab("💬 WhatsApp AI Assistant"):
331
- gr.Markdown("""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  ### WhatsApp-style AI conversation prototype
333
- Select a lead and type exactly as a customer would on WhatsApp. The AI responds, interprets the customer's intent, updates the lead status/score, and refreshes the dashboard.
334
- **No WhatsApp API is used in this prototype.** After project approval, this same workflow can be connected to WhatsApp Business.
335
- """)
 
 
 
 
 
 
 
 
 
 
336
  with gr.Row():
 
337
  wa_lead_selector = gr.Dropdown(
338
- choices=load_initial_leads()["Lead ID"].tolist(),
339
- value=load_initial_leads().iloc[0]["Lead ID"],
 
 
 
340
  label="Customer Lead",
341
  )
342
- wa_reset_btn = gr.Button("Start / Reset Conversation")
 
 
 
 
343
  wa_lead_card = gr.Markdown()
344
- wa_chat = gr.Chatbot(label="Customer ↔ AI Assistant", type="messages", height=420)
 
 
 
 
 
 
345
  with gr.Row():
 
346
  wa_customer_message = gr.Textbox(
347
  label="Type as the customer",
348
- placeholder="Example: Please send your catalogue. I have a 3BHK and would like a site visit.",
 
 
 
349
  lines=3,
350
  scale=5,
351
  )
352
- wa_send_btn = gr.Button("Send Message", variant="primary", scale=1)
 
 
 
 
 
 
353
  wa_action_panel = gr.Markdown()
 
354
  gr.Examples(
355
  examples=[
356
- ["Please send me your catalogue and previous work images."],
357
- ["I have a 3BHK apartment and my budget is around 12 lakh."],
358
- ["I have the floor plan. How can I share it?"],
359
- ["Can someone visit my apartment this Saturday?"],
360
- ["Please prepare a quotation for me."],
361
- ["I am not interested anymore."],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  ],
363
- inputs=[wa_customer_message],
364
  label="Demo customer messages",
365
  )
366
 
367
- with gr.Tab("👤 Human Intervention"):
368
- human_btn = gr.Button("Refresh Human Queue", variant="primary")
369
- human_table = gr.Dataframe(interactive=False, wrap=True, label="Leads requiring the remaining employee")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
 
371
- with gr.Tab("📊 Owner AI Daily Report"):
372
- report_btn = gr.Button("Generate Daily AI Summary", variant="primary")
373
  report = gr.Markdown()
374
 
375
- with gr.Tab("⚙️ Prototype Scope"):
376
- gr.Markdown("""
 
 
 
 
 
 
 
 
377
  ### What is real in this HF prototype
 
378
  - Excel lead upload and normalization
379
  - Attendance and assignment workflow
380
  - AI-first lead queue concept
381
  - Conversation-based lead qualification
382
- - WhatsApp-style AI customer chat with automatic lead updates
383
- - Lead score, status, summary and next-action generation
 
 
 
 
384
  - Human-intervention queue
385
  - Owner summary
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
 
387
- ### What is intentionally simulated in V1
388
- - Actual outbound PSTN/phone call
389
- - Meta lead webhook
390
- - WhatsApp Business message delivery (the HF chat simulator demonstrates the workflow without an API)
391
-
392
- The code already isolates voice calling in `services/voice_service.py`, so the simulated call can be replaced with a live provider without rewriting the lead-management application.
393
- """)
394
-
395
- # Events
396
- refresh_btn.click(refresh_dashboard, inputs=[leads_state], outputs=[k1, k2, k3, k4, k5, dashboard_table])
397
- import_event = import_btn.click(upload_excel, inputs=[excel_file], outputs=[leads_state, import_msg, lead_selector])
398
- import_event.then(lambda x: x, inputs=[leads_state], outputs=[imported_table]).then(
399
- lambda df: gr.update(choices=df["Lead ID"].tolist(), value=df.iloc[0]["Lead ID"] if len(df) else None),
400
- inputs=[leads_state],
401
- outputs=[wa_lead_selector],
402
- )
403
- allocate_btn.click(allocate, inputs=[leads_state, attendance, ai_first], outputs=[leads_state, allocation_msg]).then(lambda x: x, inputs=[leads_state], outputs=[allocation_table])
404
- lead_selector.change(lead_card, inputs=[leads_state, lead_selector], outputs=[selected_card])
405
- generate_script_btn.click(demo_script, inputs=[leads_state, lead_selector, language, scenario], outputs=[ai_opening])
406
- call_btn.click(simulate_call, inputs=[leads_state, lead_selector, phone_override, language, scenario, customer_reply], outputs=[leads_state, call_result_md, transcript, ai_summary, whatsapp_action, lead_selector])
407
- wa_lead_selector.change(lead_card, inputs=[leads_state, wa_lead_selector], outputs=[wa_lead_card])
408
  wa_reset_btn.click(
409
  reset_whatsapp_chat,
410
- inputs=[leads_state, wa_lead_selector],
411
- outputs=[wa_chat, wa_action_panel],
 
 
 
 
 
 
412
  )
 
413
  wa_event = wa_send_btn.click(
414
  whatsapp_lead_update,
415
- inputs=[leads_state, wa_lead_selector, wa_chat, wa_customer_message],
416
- outputs=[leads_state, wa_chat, wa_customer_message, wa_action_panel, wa_lead_selector],
 
 
 
 
 
 
 
 
 
 
 
417
  )
 
418
  wa_event.then(
419
  refresh_dashboard,
420
- inputs=[leads_state],
421
- outputs=[k1, k2, k3, k4, k5, dashboard_table],
 
 
 
 
 
 
 
 
 
422
  ).then(
423
  lead_card,
424
- inputs=[leads_state, wa_lead_selector],
425
- outputs=[wa_lead_card],
 
 
 
 
 
426
  ).then(
427
  human_queue,
428
- inputs=[leads_state],
429
- outputs=[human_table],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
  )
431
- human_btn.click(human_queue, inputs=[leads_state], outputs=[human_table])
432
- report_btn.click(owner_report, inputs=[leads_state], outputs=[report])
433
 
434
- demo.load(refresh_dashboard, inputs=[leads_state], outputs=[k1, k2, k3, k4, k5, dashboard_table])
435
- demo.load(lead_card, inputs=[leads_state, lead_selector], outputs=[selected_card])
436
- demo.load(lead_card, inputs=[leads_state, wa_lead_selector], outputs=[wa_lead_card])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
438
  if __name__ == "__main__":
439
- demo.launch()
 
15
  qualify_from_conversation,
16
  generate_owner_summary,
17
  )
18
+
19
  from services.voice_service import VoiceService
20
 
21
+
22
  APP_TITLE = "AI Lead Conversion Prototype | Interior Business"
23
+
24
  DATA_DIR = Path("data")
25
  DATA_DIR.mkdir(exist_ok=True)
26
+
27
  VOICE = VoiceService()
28
 
29
+ STAFF = [
30
+ "Employee 1",
31
+ "Employee 2",
32
+ "Employee 3",
33
+ "Employee 4",
34
+ ]
35
+
36
 
37
+ # =========================================================
38
+ # BASIC DATA FUNCTIONS
39
+ # =========================================================
40
 
41
  def empty_attendance():
42
+ return pd.DataFrame(
43
+ {
44
+ "Employee": STAFF,
45
+ "Attendance": [
46
+ "Present",
47
+ "Present",
48
+ "Present",
49
+ "Present",
50
+ ],
51
+ }
52
+ )
53
 
54
 
55
  def load_initial_leads():
 
59
  def kpis(df: pd.DataFrame):
60
  if df is None or df.empty:
61
  return 0, 0, 0, 0, 0
62
+
63
  total = len(df)
64
+
65
+ hot = int(
66
+ (
67
+ df.get(
68
+ "Priority",
69
+ pd.Series(dtype=str),
70
+ )
71
+ == "HOT"
72
+ ).sum()
73
+ )
74
+
75
+ qualified = int(
76
+ df.get(
77
+ "Status",
78
+ pd.Series(dtype=str),
79
+ )
80
+ .isin(
81
+ [
82
+ "Qualified",
83
+ "Site Visit Requested",
84
+ "Quote Requested",
85
+ ]
86
+ )
87
+ .sum()
88
+ )
89
+
90
+ followups = int(
91
+ df.get(
92
+ "Next Action",
93
+ pd.Series(dtype=str),
94
+ )
95
+ .astype(str)
96
+ .str.contains(
97
+ "follow|retry|callback",
98
+ case=False,
99
+ na=False,
100
+ )
101
+ .sum()
102
+ )
103
+
104
+ human = int(
105
+ df.get(
106
+ "Human Intervention",
107
+ pd.Series(dtype=str),
108
+ )
109
+ .astype(str)
110
+ .str.lower()
111
+ .isin(
112
+ [
113
+ "yes",
114
+ "true",
115
+ ]
116
+ )
117
+ .sum()
118
+ )
119
+
120
  return total, hot, qualified, followups, human
121
 
122
 
123
  def refresh_dashboard(df):
124
  total, hot, qualified, followups, human = kpis(df)
125
+
126
  return (
127
  f"### {total}\nTotal Leads",
128
  f"### {hot}\n🔥 Hot Leads",
 
133
  )
134
 
135
 
136
+ # =========================================================
137
+ # LEAD IMPORT
138
+ # =========================================================
139
+
140
  def upload_excel(file_obj):
141
  if not file_obj:
142
  df = build_demo_leads()
143
+
144
+ return (
145
+ df,
146
+ "No file selected. Demo data loaded.",
147
+ gr.update(
148
+ choices=df["Lead ID"].tolist(),
149
+ value=df.iloc[0]["Lead ID"],
150
+ ),
151
+ )
152
+
153
  try:
154
  df = normalize_excel(file_obj)
155
+
156
+ msg = (
157
+ f"Loaded {len(df)} leads from Excel and mapped "
158
+ f"the sheet into the prototype lead model."
159
+ )
160
+
161
  first = df.iloc[0]["Lead ID"] if len(df) else None
162
+
163
+ return (
164
+ df,
165
+ msg,
166
+ gr.update(
167
+ choices=df["Lead ID"].tolist(),
168
+ value=first,
169
+ ),
170
+ )
171
+
172
  except Exception as e:
173
  df = build_demo_leads()
174
+
175
+ return (
176
+ df,
177
+ f"Could not map that workbook automatically: {e}. "
178
+ f"Demo data loaded instead.",
179
+ gr.update(
180
+ choices=df["Lead ID"].tolist(),
181
+ value=df.iloc[0]["Lead ID"],
182
+ ),
183
+ )
184
 
185
 
186
+ # =========================================================
187
+ # ATTENDANCE & LEAD ALLOCATION
188
+ # =========================================================
189
+
190
  def allocate(df, attendance, ai_first):
191
  if df is None or df.empty:
192
  return df, "No leads available."
 
 
 
 
193
 
194
+ present = attendance.loc[
195
+ attendance["Attendance"]
196
+ .astype(str)
197
+ .str.lower()
198
+ == "present",
199
+ "Employee",
200
+ ].tolist()
201
+
202
+ result = assign_leads(
203
+ df.copy(),
204
+ present,
205
+ ai_first=ai_first,
206
+ )
207
+
208
+ mode = (
209
+ "AI-first qualification"
210
+ if ai_first
211
+ else "human round-robin"
212
+ )
213
+
214
+ return (
215
+ result,
216
+ f"Allocation completed using {mode}. "
217
+ f"Present staff: "
218
+ f"{', '.join(present) if present else 'None'}.",
219
+ )
220
+
221
+
222
+ # =========================================================
223
+ # LEAD HELPERS
224
+ # =========================================================
225
 
226
  def get_lead(df, lead_id):
227
  if df is None or df.empty or not lead_id:
228
  return None
229
+
230
+ row = df[
231
+ df["Lead ID"].astype(str)
232
+ == str(lead_id)
233
+ ]
234
+
235
  if row.empty:
236
  return None
237
+
238
  return row.iloc[0].to_dict()
239
 
240
 
241
  def lead_card(df, lead_id):
242
  lead = get_lead(df, lead_id)
243
+
244
  if not lead:
245
  return "Select a lead."
246
+
247
  return f"""
248
+ ### {lead.get('Customer Name', 'Customer')} — {lead.get('Lead ID', '')}
249
+
250
+ **Phone:** {lead.get('Phone', '')}
251
+ **Location:** {lead.get('Location', '')}
252
+ **Requirement:** {lead.get('Requirement', '')}
253
+ **Current Status:** {lead.get('Status', 'New')}
254
+ **Assigned To:** {lead.get('Assigned To', 'AI Queue')}
255
+ **Priority:** {lead.get('Priority', 'Unscored')}
256
+ **Lead Score:** {lead.get('Lead Score', 0)}
257
  """
258
 
259
 
260
+ # =========================================================
261
+ # AI CALLING AGENT
262
+ # =========================================================
263
+
264
+ def demo_script(
265
+ df,
266
+ lead_id,
267
+ language,
268
+ scenario,
269
+ ):
270
  lead = get_lead(df, lead_id)
271
+
272
  if not lead:
273
  return "Select a lead first."
274
+
275
+ name = (
276
+ lead.get("Customer Name")
277
+ or "there"
278
+ )
279
+
280
+ requirement = (
281
+ lead.get("Requirement")
282
+ or "interior requirement"
283
+ )
284
+
285
  intro = {
286
+ "English":
287
+ (
288
+ f"Hello {name}. "
289
+ f"I’m the automated assistant from the interior design team. "
290
+ f"You recently submitted an enquiry regarding {requirement}. "
291
+ f"Is this a good time for a quick 2-minute discussion?"
292
+ ),
293
+
294
+ "Kannada + English":
295
+ (
296
+ f"Hello {name}. "
297
+ f"Naanu interior design team-na automated assistant. "
298
+ f"Neevu recently {requirement} bagge enquiry submit maadidri. "
299
+ f"Iga 2 minutes maatadakke convenient-aa?"
300
+ ),
301
+
302
+ "Hindi + English":
303
+ (
304
+ f"Hello {name}. "
305
+ f"Main interior design team ka automated assistant hoon. "
306
+ f"Aapne recently {requirement} ke liye enquiry submit ki thi. "
307
+ f"Kya abhi 2 minute baat karna convenient hai?"
308
+ ),
309
+
310
+ }.get(
311
+ language,
312
+ "Hello. I’m the automated assistant from the interior design team.",
313
+ )
314
+
315
  prompts = {
316
+ "Full qualification":
317
+ (
318
+ "I’ll understand your property, location, timeline, "
319
+ "approximate budget, whether you have a floor plan, "
320
+ "and whether you would like a catalogue, quotation "
321
+ "or site visit."
322
+ ),
323
+
324
+ "Site visit interest":
325
+ (
326
+ "I’ll quickly confirm your property details "
327
+ "and whether you would like our team to arrange a site visit."
328
+ ),
329
+
330
+ "Catalogue request":
331
+ (
332
+ "I’ll understand your requirement and can arrange "
333
+ "for our catalogue and previous work references to be sent."
334
+ ),
335
+
336
+ "No answer / callback":
337
+ (
338
+ "This scenario demonstrates a missed call or "
339
+ "callback request and automatic scheduling."
340
+ ),
341
  }
 
342
 
343
+ return (
344
+ intro
345
+ + "\n\n"
346
+ + prompts.get(
347
+ scenario,
348
+ prompts["Full qualification"],
349
+ )
350
+ )
351
+
352
+
353
+ def simulate_call(
354
+ df,
355
+ lead_id,
356
+ phone_override,
357
+ language,
358
+ scenario,
359
+ customer_reply,
360
+ ):
361
+ lead = get_lead(
362
+ df,
363
+ lead_id,
364
+ )
365
 
 
 
366
  if not lead:
367
+ return (
368
+ df,
369
+ "No lead selected.",
370
+ "",
371
+ "",
372
+ "",
373
+ gr.update(),
374
+ )
375
+
376
+ phone = (
377
+ phone_override
378
+ or lead.get("Phone")
379
+ or ""
380
+ ).strip()
381
 
 
382
  if not phone:
383
+ return (
384
+ df,
385
+ "Enter a controlled test phone number.",
386
+ "",
387
+ "",
388
+ "",
389
+ gr.update(),
390
+ )
391
 
392
  call_result = VOICE.start_call(
393
  phone=phone,
 
397
  customer_reply=customer_reply,
398
  )
399
 
400
+ qualification = qualify_from_conversation(
401
+ lead,
402
+ call_result["transcript"],
403
+ scenario=scenario,
404
+ )
405
+
406
  out = df.copy()
407
+
408
+ idx = out.index[
409
+ out["Lead ID"].astype(str)
410
+ == str(lead_id)
411
+ ][0]
412
+
413
  for key, value in qualification.items():
414
  if key in out.columns:
415
  out.at[idx, key] = value
416
+
417
+ out.at[
418
+ idx,
419
+ "Last Contact",
420
+ ] = datetime.now().strftime(
421
+ "%Y-%m-%d %H:%M"
422
+ )
423
+
424
+ out.at[
425
+ idx,
426
+ "Call Result",
427
+ ] = call_result["result"]
428
 
429
  result_md = f"""
430
  ### ✅ AI Qualification Completed
431
+
432
  **Call mode:** {call_result['mode']}
433
  **Outcome:** {call_result['result']}
434
  **Status:** {qualification['Status']}
 
437
  **Next Action:** {qualification['Next Action']}
438
  **Human Intervention:** {qualification['Human Intervention']}
439
  """
440
+
441
  summary = qualification["AI Summary"]
 
 
 
442
 
443
+ wa = qualification.get(
444
+ "WhatsApp Action",
445
+ "No WhatsApp action required",
446
+ )
447
 
448
+ choices = out[
449
+ "Lead ID"
450
+ ].tolist()
451
+
452
+ return (
453
+ out,
454
+ result_md,
455
+ call_result["transcript"],
456
+ summary,
457
+ wa,
458
+ gr.update(
459
+ choices=choices,
460
+ value=lead_id,
461
+ ),
462
+ )
463
+
464
+
465
+ # =========================================================
466
+ # WHATSAPP AI ASSISTANT
467
+ # =========================================================
468
+
469
+ def whatsapp_lead_update(
470
+ df,
471
+ lead_id,
472
+ history,
473
+ customer_message,
474
+ ):
475
+ """
476
+ Simulate a WhatsApp Business conversation
477
+ while using the same lead engine.
478
+ """
479
+
480
+ lead = get_lead(
481
+ df,
482
+ lead_id,
483
+ )
484
 
 
 
 
485
  history = history or []
486
+
487
+ message = (
488
+ customer_message
489
+ or ""
490
+ ).strip()
491
+
492
  if not lead:
493
+ return (
494
+ df,
495
+ history,
496
+ "",
497
+ "Select a lead first.",
498
+ gr.update(),
499
+ )
500
+
501
  if not message:
502
+ return (
503
+ df,
504
+ history,
505
+ "",
506
+ "Type a customer message.",
507
+ gr.update(),
508
+ )
509
 
510
  previous_customer_text = " ".join(
511
+ str(
512
+ item.get(
513
+ "content",
514
+ "",
515
+ )
516
+ )
517
+ for item in history
518
+ if isinstance(
519
+ item,
520
+ dict,
521
+ )
522
+ and item.get(
523
+ "role"
524
+ )
525
+ == "user"
526
+ )
527
+
528
+ customer_context = (
529
+ previous_customer_text
530
+ + " "
531
+ + message
532
+ ).strip()
533
+
534
+ qualification = qualify_from_conversation(
535
+ lead,
536
+ customer_context,
537
+ scenario="Full qualification",
538
  )
 
 
539
 
540
  lower = message.lower()
541
+
542
+ name = (
543
+ lead.get(
544
+ "Customer Name"
545
+ )
546
+ or "there"
547
+ )
548
+
549
+ if any(
550
+ x in lower
551
+ for x in [
552
+ "not interested",
553
+ "no requirement",
554
+ "don't need",
555
+ "do not need",
556
+ ]
557
+ ):
558
+ reply = (
559
+ f"Understood, {name}. "
560
+ f"I’ll close this enquiry for now. "
561
+ f"Thank you for your time."
562
+ )
563
+
564
+ elif any(
565
+ x in lower
566
+ for x in [
567
+ "site visit",
568
+ "visit my",
569
+ "visit the site",
570
+ "come and visit",
571
+ "someone to visit",
572
+ ]
573
+ ):
574
+ reply = (
575
+ "Certainly. I’ve marked this as a site-visit request. "
576
+ "Our human coordinator will confirm the available "
577
+ "date and time with you."
578
+ )
579
+
580
+ elif any(
581
+ x in lower
582
+ for x in [
583
+ "quotation",
584
+ "quote",
585
+ "estimate",
586
+ ]
587
+ ):
588
+ reply = (
589
+ "Sure. I’ve recorded your quotation request. "
590
+ "I’ll collect the required details and route this "
591
+ "to our team for review before the quotation is shared."
592
+ )
593
+
594
+ elif any(
595
+ x in lower
596
+ for x in [
597
+ "catalog",
598
+ "catalogue",
599
+ "portfolio",
600
+ "previous work",
601
+ "images",
602
+ "photos",
603
+ "designs",
604
+ ]
605
+ ):
606
+ reply = (
607
+ "Absolutely. I’ve noted that you would like our "
608
+ "catalogue / previous-work references. "
609
+ "In production, the approved material would be "
610
+ "sent here automatically."
611
+ )
612
+
613
+ elif any(
614
+ x in lower
615
+ for x in [
616
+ "floor plan",
617
+ "floorplan",
618
+ ]
619
+ ):
620
+ reply = (
621
+ "Great. Please share the floor plan here when convenient. "
622
+ "The production WhatsApp integration can attach it "
623
+ "directly to your lead record for the design team."
624
+ )
625
+
626
+ elif re.search(
627
+ r"\b\d+(?:\.\d+)?\s*(?:lakh|lac|lakhs|lacs)\b",
628
+ lower,
629
+ ):
630
+ reply = (
631
+ "Thank you. I’ve captured your approximate budget. "
632
+ "Could you also tell me your property type and "
633
+ "when you would like the interior work to begin?"
634
+ )
635
+
636
+ elif any(
637
+ x in lower
638
+ for x in [
639
+ "3bhk",
640
+ "3 bhk",
641
+ "2bhk",
642
+ "2 bhk",
643
+ "1bhk",
644
+ "1 bhk",
645
+ "villa",
646
+ "apartment",
647
+ "house",
648
+ ]
649
+ ):
650
+ reply = (
651
+ "Thanks, I’ve captured the property details. "
652
+ "Do you have an approximate budget, expected timeline, "
653
+ "or floor plan available?"
654
+ )
655
+
656
+ elif any(
657
+ x in lower
658
+ for x in [
659
+ "hello",
660
+ "hi",
661
+ "hey",
662
+ ]
663
+ ):
664
+ reply = (
665
+ f"Hello {name}! "
666
+ f"I’m the AI assistant for the interior design team. "
667
+ f"I can help with your requirement, catalogue, "
668
+ f"floor plan, quotation, follow-up, or site-visit request. "
669
+ f"How can I help?"
670
+ )
671
+
672
  else:
673
+ reply = (
674
+ "Thanks for the information. "
675
+ "I’ve added it to your enquiry. "
676
+ "Could you share your property type, approximate budget, "
677
+ "expected timeline, or whether you need a catalogue, "
678
+ "quotation, or site visit?"
679
+ )
680
 
681
  out = df.copy()
682
+
683
+ idx = out.index[
684
+ out["Lead ID"].astype(str)
685
+ == str(lead_id)
686
+ ][0]
687
+
688
  for key, value in qualification.items():
689
  if key in out.columns:
690
+ out.at[
691
+ idx,
692
+ key,
693
+ ] = value
694
+
695
+ out.at[
696
+ idx,
697
+ "Last Contact",
698
+ ] = datetime.now().strftime(
699
+ "%Y-%m-%d %H:%M"
700
+ )
701
+
702
+ out.at[
703
+ idx,
704
+ "Call Result",
705
+ ] = "WhatsApp prototype interaction"
706
 
707
  new_history = history + [
708
+ {
709
+ "role": "user",
710
+ "content": message,
711
+ },
712
+ {
713
+ "role": "assistant",
714
+ "content": reply,
715
+ },
716
  ]
717
+
718
  action_md = f"""
719
  ### AI Action
720
+
721
  **Detected Status:** {qualification['Status']}
722
  **Priority:** {qualification['Priority']}
723
  **Lead Score:** {qualification['Lead Score']}/100
 
727
  **Production channel:** WhatsApp Business API
728
  **Prototype channel:** HF chat simulator
729
  """
730
+
731
+ return (
732
+ out,
733
+ new_history,
734
+ "",
735
+ action_md,
736
+ gr.update(
737
+ choices=out[
738
+ "Lead ID"
739
+ ].tolist(),
740
+ value=lead_id,
741
+ ),
742
+ )
743
 
744
 
745
+ def reset_whatsapp_chat(
746
+ df,
747
+ lead_id,
748
+ ):
749
+ lead = get_lead(
750
+ df,
751
+ lead_id,
752
+ )
753
+
754
  if not lead:
755
+ return (
756
+ [],
757
+ "Select a lead first.",
758
+ )
759
+
760
+ name = (
761
+ lead.get(
762
+ "Customer Name"
763
+ )
764
+ or "there"
765
+ )
766
+
767
+ req = (
768
+ lead.get(
769
+ "Requirement"
770
+ )
771
+ or "your interior requirement"
772
+ )
773
+
774
  opening = (
775
+ f"Hello {name}! "
776
+ f"I’m the AI assistant for the interior design team. "
777
  f"I’m following up on your enquiry about {req}. "
778
+ f"I can help with requirements, catalogue, floor plan, "
779
+ f"quotation, follow-up, or a site visit. "
780
+ f"How can I help?"
781
+ )
782
+
783
+ return (
784
+ [
785
+ {
786
+ "role": "assistant",
787
+ "content": opening,
788
+ }
789
+ ],
790
+ "Conversation reset. Lead data is unchanged.",
791
  )
 
792
 
793
 
794
+ # =========================================================
795
+ # HUMAN INTERVENTION
796
+ # =========================================================
797
+
798
  def human_queue(df):
799
  if df is None or df.empty:
800
  return pd.DataFrame()
801
+
802
+ mask = (
803
+ df[
804
+ "Human Intervention"
805
+ ]
806
+ .astype(str)
807
+ .str.lower()
808
+ .isin(
809
+ [
810
+ "yes",
811
+ "true",
812
+ ]
813
+ )
814
+ )
815
+
816
+ cols = [
817
+ "Lead ID",
818
+ "Customer Name",
819
+ "Phone",
820
+ "Location",
821
+ "Requirement",
822
+ "Status",
823
+ "Priority",
824
+ "Lead Score",
825
+ "Next Action",
826
+ "AI Summary",
827
+ ]
828
+
829
+ return (
830
+ df.loc[
831
+ mask,
832
+ [
833
+ c
834
+ for c in cols
835
+ if c in df.columns
836
+ ],
837
+ ]
838
+ .sort_values(
839
+ [
840
+ "Lead Score"
841
+ ],
842
+ ascending=False,
843
+ )
844
+ )
845
 
846
 
847
+ # =========================================================
848
+ # OWNER REPORT
849
+ # =========================================================
850
+
851
  def owner_report(df):
852
  return generate_owner_summary(df)
853
 
854
 
855
+ # =========================================================
856
+ # PROCELEVATE BRAND CSS
857
+ # =========================================================
858
+
859
  CSS = """
860
+ .gradio-container {
861
+ max-width: 1500px !important;
862
+ }
863
+
864
+ /* KPI Cards */
865
+ .kpi {
866
+ border: 1px solid #d9e1ea;
867
+ border-radius: 14px;
868
+ padding: 14px;
869
+ min-height: 95px;
870
+ background: white;
871
+ }
872
+
873
+ /* Procelevate Brand Header */
874
+ .hero {
875
+ background: #0F2C59 !important;
876
+ color: #FFFFFF !important;
877
+ padding: 22px;
878
+ border-radius: 18px;
879
+ margin-bottom: 12px;
880
+ }
881
+
882
+ /* Header Main Title */
883
+ .hero h1 {
884
+ color: #FFFFFF !important;
885
+ margin: 0 !important;
886
+ font-weight: 700;
887
+ }
888
+
889
+ /* Header Subtitle */
890
+ .hero p {
891
+ color: #FFFFFF !important;
892
+ margin: 7px 0 0 !important;
893
+ opacity: 1 !important;
894
+ }
895
+
896
+ /* Small Notes */
897
+ .small-note {
898
+ font-size: 12px;
899
+ opacity: .8;
900
+ }
901
  """
902
 
 
 
903
 
904
+ # =========================================================
905
+ # GRADIO APPLICATION
906
+ # =========================================================
907
+
908
+ with gr.Blocks(
909
+ title=APP_TITLE,
910
+ css=CSS,
911
+ theme=gr.themes.Soft(),
912
+ ) as demo:
913
+
914
+ leads_state = gr.State(
915
+ load_initial_leads()
916
+ )
917
+
918
+ # -----------------------------------------------------
919
+ # PROCELEVATE HERO HEADER
920
+ # -----------------------------------------------------
921
+
922
+ gr.HTML(
923
+ """
924
+ <div class="hero">
925
+ <h1>
926
+ AI-Powered Lead Conversion & Customer Engagement
927
+ </h1>
928
+
929
+ <p>
930
+ Interior Business •
931
+ Meta Lead →
932
+ AI Qualification →
933
+ Status →
934
+ WhatsApp Action →
935
+ Human Handoff
936
+ </p>
937
+ </div>
938
+ """
939
+ )
940
+
941
+ # =====================================================
942
+ # DASHBOARD
943
+ # =====================================================
944
+
945
+ with gr.Tab(
946
+ "🏠 Dashboard"
947
+ ):
948
 
 
949
  with gr.Row():
950
+
951
+ k1 = gr.Markdown(
952
+ elem_classes="kpi"
953
+ )
954
+
955
+ k2 = gr.Markdown(
956
+ elem_classes="kpi"
957
+ )
958
+
959
+ k3 = gr.Markdown(
960
+ elem_classes="kpi"
961
+ )
962
+
963
+ k4 = gr.Markdown(
964
+ elem_classes="kpi"
965
+ )
966
+
967
+ k5 = gr.Markdown(
968
+ elem_classes="kpi"
969
+ )
970
+
971
+ dashboard_table = gr.Dataframe(
972
+ interactive=False,
973
+ wrap=True,
974
+ label="Lead Pipeline",
975
+ )
976
+
977
+ refresh_btn = gr.Button(
978
+ "Refresh Dashboard",
979
+ variant="primary",
980
+ )
981
+
982
+ # =====================================================
983
+ # LEAD IMPORT
984
+ # =====================================================
985
+
986
+ with gr.Tab(
987
+ "📥 Lead Import"
988
+ ):
989
+
990
+ gr.Markdown(
991
+ """
992
+ Upload the client's Excel sheet.
993
+
994
+ The prototype maps the incoming Facebook / Instagram lead data
995
+ into the AI lead-management workflow.
996
+ """
997
+ )
998
+
999
+ excel_file = gr.File(
1000
+ label="Upload Excel (.xlsx/.xls)",
1001
+ file_types=[
1002
+ ".xlsx",
1003
+ ".xls",
1004
+ ],
1005
+ type="filepath",
1006
+ )
1007
+
1008
+ import_btn = gr.Button(
1009
+ "Load Leads",
1010
+ variant="primary",
1011
+ )
1012
+
1013
  import_msg = gr.Markdown()
 
1014
 
1015
+ imported_table = gr.Dataframe(
1016
+ interactive=False,
1017
+ wrap=True,
1018
+ )
1019
+
1020
+ # =====================================================
1021
+ # ATTENDANCE & ALLOCATION
1022
+ # =====================================================
1023
+
1024
+ with gr.Tab(
1025
+ "👥 Attendance & Allocation"
1026
+ ):
1027
+
1028
+ gr.Markdown(
1029
+ """
1030
+ Mark attendance first.
1031
+
1032
+ In AI-first mode, new leads go to the AI qualification queue
1033
+ instead of being distributed to all four callers.
1034
+ """
1035
+ )
1036
+
1037
  attendance = gr.Dataframe(
1038
  value=empty_attendance(),
1039
+ headers=[
1040
+ "Employee",
1041
+ "Attendance",
1042
+ ],
1043
+ datatype=[
1044
+ "str",
1045
+ "str",
1046
+ ],
1047
  interactive=True,
1048
  label="Today's Attendance",
1049
  )
1050
+
1051
+ ai_first = gr.Checkbox(
1052
+ value=True,
1053
+ label="AI-first qualification mode",
1054
+ )
1055
+
1056
+ allocate_btn = gr.Button(
1057
+ "Allocate Today's Leads",
1058
+ variant="primary",
1059
+ )
1060
+
1061
  allocation_msg = gr.Markdown()
 
1062
 
1063
+ allocation_table = gr.Dataframe(
1064
+ interactive=False,
1065
+ wrap=True,
1066
+ )
1067
+
1068
+ # =====================================================
1069
+ # AI CALLING AGENT
1070
+ # =====================================================
1071
+
1072
+ with gr.Tab(
1073
+ "📞 AI Calling Agent"
1074
+ ):
1075
+
1076
+ gr.Markdown(
1077
+ """
1078
+ For this HF prototype, the conversation and call outcome
1079
+ are simulated.
1080
+
1081
+ The production solution can connect the same workflow
1082
+ to a real Voice AI / telephony provider.
1083
+ """
1084
+ )
1085
+
1086
  with gr.Row():
1087
+
1088
+ lead_selector = gr.Dropdown(
1089
+ choices=load_initial_leads()[
1090
+ "Lead ID"
1091
+ ].tolist(),
1092
+ value=load_initial_leads()
1093
+ .iloc[0]["Lead ID"],
1094
+ label="Lead",
1095
+ )
1096
+
1097
+ phone_override = gr.Textbox(
1098
+ label="Controlled Test Phone Number",
1099
+ placeholder=(
1100
+ "Enter your business number "
1101
+ "for later live-call integration"
1102
+ ),
1103
+ )
1104
+
1105
+ language = gr.Dropdown(
1106
+ [
1107
+ "English",
1108
+ "Kannada + English",
1109
+ "Hindi + English",
1110
+ ],
1111
+ value="English",
1112
+ label="Conversation Language",
1113
+ )
1114
+
1115
+ scenario = gr.Dropdown(
1116
+ [
1117
+ "Full qualification",
1118
+ "Site visit interest",
1119
+ "Catalogue request",
1120
+ "No answer / callback",
1121
+ ],
1122
+ value="Full qualification",
1123
+ label="Demo Scenario",
1124
+ )
1125
+
1126
  selected_card = gr.Markdown()
1127
+
1128
+ generate_script_btn = gr.Button(
1129
+ "Generate AI Opening"
1130
+ )
1131
+
1132
+ ai_opening = gr.Textbox(
1133
+ label="AI Opening / Conversation Goal",
1134
+ lines=5,
1135
+ )
1136
+
1137
  customer_reply = gr.Textbox(
1138
+ label=(
1139
+ "Your Demo Reply "
1140
+ "(act as the customer)"
1141
+ ),
1142
  lines=7,
1143
+ value=(
1144
+ "Yes, I have a 3BHK apartment in Banashankari. "
1145
+ "Possession is next month. "
1146
+ "My budget is around 12 lakh. "
1147
+ "I have the floor plan. "
1148
+ "Please send me your catalogue and "
1149
+ "I would also like someone to visit the site."
1150
+ ),
1151
  )
1152
+
1153
+ call_btn = gr.Button(
1154
+ "🤖 Run AI Qualification Call",
1155
+ variant="primary",
1156
+ )
1157
+
1158
  call_result_md = gr.Markdown()
1159
+
1160
  with gr.Row():
 
 
 
1161
 
1162
+ transcript = gr.Textbox(
1163
+ label="Call Transcript",
1164
+ lines=12,
1165
+ )
1166
+
1167
+ ai_summary = gr.Textbox(
1168
+ label="AI Call Summary",
1169
+ lines=12,
1170
+ )
1171
+
1172
+ whatsapp_action = gr.Textbox(
1173
+ label=(
1174
+ "Automatic WhatsApp / "
1175
+ "Workflow Action"
1176
+ ),
1177
+ lines=4,
1178
+ )
1179
+
1180
+ # =====================================================
1181
+ # WHATSAPP AI ASSISTANT
1182
+ # =====================================================
1183
+
1184
+ with gr.Tab(
1185
+ "💬 WhatsApp AI Assistant"
1186
+ ):
1187
+
1188
+ gr.Markdown(
1189
+ """
1190
  ### WhatsApp-style AI conversation prototype
1191
+
1192
+ Select a lead and type exactly as a customer would on WhatsApp.
1193
+
1194
+ The AI responds, interprets the customer's intent,
1195
+ updates the lead status / score and refreshes the dashboard.
1196
+
1197
+ **No WhatsApp API is used in this prototype.**
1198
+
1199
+ After project approval, the same workflow can be connected
1200
+ to WhatsApp Business.
1201
+ """
1202
+ )
1203
+
1204
  with gr.Row():
1205
+
1206
  wa_lead_selector = gr.Dropdown(
1207
+ choices=load_initial_leads()[
1208
+ "Lead ID"
1209
+ ].tolist(),
1210
+ value=load_initial_leads()
1211
+ .iloc[0]["Lead ID"],
1212
  label="Customer Lead",
1213
  )
1214
+
1215
+ wa_reset_btn = gr.Button(
1216
+ "Start / Reset Conversation"
1217
+ )
1218
+
1219
  wa_lead_card = gr.Markdown()
1220
+
1221
+ wa_chat = gr.Chatbot(
1222
+ label="Customer ↔ AI Assistant",
1223
+ type="messages",
1224
+ height=420,
1225
+ )
1226
+
1227
  with gr.Row():
1228
+
1229
  wa_customer_message = gr.Textbox(
1230
  label="Type as the customer",
1231
+ placeholder=(
1232
+ "Example: Please send your catalogue. "
1233
+ "I have a 3BHK and would like a site visit."
1234
+ ),
1235
  lines=3,
1236
  scale=5,
1237
  )
1238
+
1239
+ wa_send_btn = gr.Button(
1240
+ "Send Message",
1241
+ variant="primary",
1242
+ scale=1,
1243
+ )
1244
+
1245
  wa_action_panel = gr.Markdown()
1246
+
1247
  gr.Examples(
1248
  examples=[
1249
+ [
1250
+ "Please send me your catalogue "
1251
+ "and previous work images."
1252
+ ],
1253
+ [
1254
+ "I have a 3BHK apartment and "
1255
+ "my budget is around 12 lakh."
1256
+ ],
1257
+ [
1258
+ "I have the floor plan. "
1259
+ "How can I share it?"
1260
+ ],
1261
+ [
1262
+ "Can someone visit my apartment "
1263
+ "this Saturday?"
1264
+ ],
1265
+ [
1266
+ "Please prepare a quotation for me."
1267
+ ],
1268
+ [
1269
+ "I am not interested anymore."
1270
+ ],
1271
+ ],
1272
+ inputs=[
1273
+ wa_customer_message
1274
  ],
 
1275
  label="Demo customer messages",
1276
  )
1277
 
1278
+ # =====================================================
1279
+ # HUMAN INTERVENTION
1280
+ # =====================================================
1281
+
1282
+ with gr.Tab(
1283
+ "👤 Human Intervention"
1284
+ ):
1285
+
1286
+ human_btn = gr.Button(
1287
+ "Refresh Human Queue",
1288
+ variant="primary",
1289
+ )
1290
+
1291
+ human_table = gr.Dataframe(
1292
+ interactive=False,
1293
+ wrap=True,
1294
+ label=(
1295
+ "Leads requiring "
1296
+ "the remaining employee"
1297
+ ),
1298
+ )
1299
+
1300
+ # =====================================================
1301
+ # OWNER DAILY REPORT
1302
+ # =====================================================
1303
+
1304
+ with gr.Tab(
1305
+ "📊 Owner AI Daily Report"
1306
+ ):
1307
+
1308
+ report_btn = gr.Button(
1309
+ "Generate Daily AI Summary",
1310
+ variant="primary",
1311
+ )
1312
 
 
 
1313
  report = gr.Markdown()
1314
 
1315
+ # =====================================================
1316
+ # PROTOTYPE SCOPE
1317
+ # =====================================================
1318
+
1319
+ with gr.Tab(
1320
+ "⚙️ Prototype Scope"
1321
+ ):
1322
+
1323
+ gr.Markdown(
1324
+ """
1325
  ### What is real in this HF prototype
1326
+
1327
  - Excel lead upload and normalization
1328
  - Attendance and assignment workflow
1329
  - AI-first lead queue concept
1330
  - Conversation-based lead qualification
1331
+ - WhatsApp-style AI customer chat
1332
+ - Automatic lead updates
1333
+ - Lead scoring
1334
+ - Lead status classification
1335
+ - AI summary
1336
+ - Next-action generation
1337
  - Human-intervention queue
1338
  - Owner summary
1339
+ - Automatic dashboard refresh
1340
+
1341
+ ### What is intentionally simulated in the prototype
1342
+
1343
+ - Actual outbound PSTN / phone call
1344
+ - Meta lead webhook / live Meta API
1345
+ - WhatsApp Business message delivery
1346
+ - Live quotation sending
1347
+ - Calendar scheduling
1348
+ - Site-visit calendar blocking
1349
+ - Automated production reminders
1350
+
1351
+ The production solution can connect these APIs
1352
+ without changing the core lead-management workflow.
1353
+ """
1354
+ )
1355
+
1356
+ # =====================================================
1357
+ # EVENTS
1358
+ # =====================================================
1359
+
1360
+ refresh_btn.click(
1361
+ refresh_dashboard,
1362
+ inputs=[
1363
+ leads_state
1364
+ ],
1365
+ outputs=[
1366
+ k1,
1367
+ k2,
1368
+ k3,
1369
+ k4,
1370
+ k5,
1371
+ dashboard_table,
1372
+ ],
1373
+ )
1374
+
1375
+ # ---------------- LEAD IMPORT ----------------
1376
+
1377
+ import_event = import_btn.click(
1378
+ upload_excel,
1379
+ inputs=[
1380
+ excel_file
1381
+ ],
1382
+ outputs=[
1383
+ leads_state,
1384
+ import_msg,
1385
+ lead_selector,
1386
+ ],
1387
+ )
1388
+
1389
+ import_event.then(
1390
+ lambda x: x,
1391
+ inputs=[
1392
+ leads_state
1393
+ ],
1394
+ outputs=[
1395
+ imported_table
1396
+ ],
1397
+ ).then(
1398
+ lambda df: gr.update(
1399
+ choices=df[
1400
+ "Lead ID"
1401
+ ].tolist(),
1402
+ value=(
1403
+ df.iloc[0][
1404
+ "Lead ID"
1405
+ ]
1406
+ if len(df)
1407
+ else None
1408
+ ),
1409
+ ),
1410
+ inputs=[
1411
+ leads_state
1412
+ ],
1413
+ outputs=[
1414
+ wa_lead_selector
1415
+ ],
1416
+ )
1417
+
1418
+ # ---------------- ALLOCATION ----------------
1419
+
1420
+ allocate_btn.click(
1421
+ allocate,
1422
+ inputs=[
1423
+ leads_state,
1424
+ attendance,
1425
+ ai_first,
1426
+ ],
1427
+ outputs=[
1428
+ leads_state,
1429
+ allocation_msg,
1430
+ ],
1431
+ ).then(
1432
+ lambda x: x,
1433
+ inputs=[
1434
+ leads_state
1435
+ ],
1436
+ outputs=[
1437
+ allocation_table
1438
+ ],
1439
+ )
1440
+
1441
+ # ---------------- AI CALLING ----------------
1442
+
1443
+ lead_selector.change(
1444
+ lead_card,
1445
+ inputs=[
1446
+ leads_state,
1447
+ lead_selector,
1448
+ ],
1449
+ outputs=[
1450
+ selected_card
1451
+ ],
1452
+ )
1453
+
1454
+ generate_script_btn.click(
1455
+ demo_script,
1456
+ inputs=[
1457
+ leads_state,
1458
+ lead_selector,
1459
+ language,
1460
+ scenario,
1461
+ ],
1462
+ outputs=[
1463
+ ai_opening
1464
+ ],
1465
+ )
1466
+
1467
+ call_event = call_btn.click(
1468
+ simulate_call,
1469
+ inputs=[
1470
+ leads_state,
1471
+ lead_selector,
1472
+ phone_override,
1473
+ language,
1474
+ scenario,
1475
+ customer_reply,
1476
+ ],
1477
+ outputs=[
1478
+ leads_state,
1479
+ call_result_md,
1480
+ transcript,
1481
+ ai_summary,
1482
+ whatsapp_action,
1483
+ lead_selector,
1484
+ ],
1485
+ )
1486
+
1487
+ # Refresh dashboard automatically after AI call
1488
+ call_event.then(
1489
+ refresh_dashboard,
1490
+ inputs=[
1491
+ leads_state
1492
+ ],
1493
+ outputs=[
1494
+ k1,
1495
+ k2,
1496
+ k3,
1497
+ k4,
1498
+ k5,
1499
+ dashboard_table,
1500
+ ],
1501
+ ).then(
1502
+ lead_card,
1503
+ inputs=[
1504
+ leads_state,
1505
+ lead_selector,
1506
+ ],
1507
+ outputs=[
1508
+ selected_card
1509
+ ],
1510
+ ).then(
1511
+ human_queue,
1512
+ inputs=[
1513
+ leads_state
1514
+ ],
1515
+ outputs=[
1516
+ human_table
1517
+ ],
1518
+ )
1519
+
1520
+ # ---------------- WHATSAPP ----------------
1521
+
1522
+ wa_lead_selector.change(
1523
+ lead_card,
1524
+ inputs=[
1525
+ leads_state,
1526
+ wa_lead_selector,
1527
+ ],
1528
+ outputs=[
1529
+ wa_lead_card
1530
+ ],
1531
+ )
1532
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1533
  wa_reset_btn.click(
1534
  reset_whatsapp_chat,
1535
+ inputs=[
1536
+ leads_state,
1537
+ wa_lead_selector,
1538
+ ],
1539
+ outputs=[
1540
+ wa_chat,
1541
+ wa_action_panel,
1542
+ ],
1543
  )
1544
+
1545
  wa_event = wa_send_btn.click(
1546
  whatsapp_lead_update,
1547
+ inputs=[
1548
+ leads_state,
1549
+ wa_lead_selector,
1550
+ wa_chat,
1551
+ wa_customer_message,
1552
+ ],
1553
+ outputs=[
1554
+ leads_state,
1555
+ wa_chat,
1556
+ wa_customer_message,
1557
+ wa_action_panel,
1558
+ wa_lead_selector,
1559
+ ],
1560
  )
1561
+
1562
  wa_event.then(
1563
  refresh_dashboard,
1564
+ inputs=[
1565
+ leads_state
1566
+ ],
1567
+ outputs=[
1568
+ k1,
1569
+ k2,
1570
+ k3,
1571
+ k4,
1572
+ k5,
1573
+ dashboard_table,
1574
+ ],
1575
  ).then(
1576
  lead_card,
1577
+ inputs=[
1578
+ leads_state,
1579
+ wa_lead_selector,
1580
+ ],
1581
+ outputs=[
1582
+ wa_lead_card
1583
+ ],
1584
  ).then(
1585
  human_queue,
1586
+ inputs=[
1587
+ leads_state
1588
+ ],
1589
+ outputs=[
1590
+ human_table
1591
+ ],
1592
+ )
1593
+
1594
+ # ---------------- HUMAN QUEUE ----------------
1595
+
1596
+ human_btn.click(
1597
+ human_queue,
1598
+ inputs=[
1599
+ leads_state
1600
+ ],
1601
+ outputs=[
1602
+ human_table
1603
+ ],
1604
+ )
1605
+
1606
+ # ---------------- OWNER REPORT ----------------
1607
+
1608
+ report_btn.click(
1609
+ owner_report,
1610
+ inputs=[
1611
+ leads_state
1612
+ ],
1613
+ outputs=[
1614
+ report
1615
+ ],
1616
  )
 
 
1617
 
1618
+ # =====================================================
1619
+ # INITIAL LOAD
1620
+ # =====================================================
1621
+
1622
+ demo.load(
1623
+ refresh_dashboard,
1624
+ inputs=[
1625
+ leads_state
1626
+ ],
1627
+ outputs=[
1628
+ k1,
1629
+ k2,
1630
+ k3,
1631
+ k4,
1632
+ k5,
1633
+ dashboard_table,
1634
+ ],
1635
+ )
1636
+
1637
+ demo.load(
1638
+ lead_card,
1639
+ inputs=[
1640
+ leads_state,
1641
+ lead_selector,
1642
+ ],
1643
+ outputs=[
1644
+ selected_card
1645
+ ],
1646
+ )
1647
+
1648
+ demo.load(
1649
+ lead_card,
1650
+ inputs=[
1651
+ leads_state,
1652
+ wa_lead_selector,
1653
+ ],
1654
+ outputs=[
1655
+ wa_lead_card
1656
+ ],
1657
+ )
1658
+
1659
+
1660
+ # =========================================================
1661
+ # RUN APPLICATION
1662
+ # =========================================================
1663
 
1664
  if __name__ == "__main__":
1665
+ demo.launch()