Download app.py from MBG0903/Interior_AI_Lead_Agent: direct link, hf CLI and curl.
- Browser
- Download file 36.4 kB
-
https://huggingface.co/spaces/MBG0903/Interior_AI_Lead_Agent/resolve/main/app.py
- Command line
-
hf download hf://spaces/MBG0903/Interior_AI_Lead_Agent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MBG0903/Interior_AI_Lead_Agent/resolve/main/app.py
36.4 kB
import os
import re
import json
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Tuple
import gradio as gr
import pandas as pd
from services.lead_logic import (
normalize_excel,
build_demo_leads,
assign_leads,
qualify_from_conversation,
generate_owner_summary,
)
from services.voice_service import VoiceService
APP_TITLE = "AI Lead Conversion Prototype | Interior Business"
DATA_DIR = Path("data")
DATA_DIR.mkdir(exist_ok=True)
VOICE = VoiceService()
STAFF = [
"Employee 1",
"Employee 2",
"Employee 3",
"Employee 4",
]
# =========================================================
# BASIC DATA FUNCTIONS
# =========================================================
def empty_attendance():
return pd.DataFrame(
{
"Employee": STAFF,
"Attendance": [
"Present",
"Present",
"Present",
"Present",
],
}
)
def load_initial_leads():
return build_demo_leads()
def kpis(df: pd.DataFrame):
if df is None or df.empty:
return 0, 0, 0, 0, 0
total = len(df)
hot = int(
(
df.get(
"Priority",
pd.Series(dtype=str),
)
== "HOT"
).sum()
)
qualified = int(
df.get(
"Status",
pd.Series(dtype=str),
)
.isin(
[
"Qualified",
"Site Visit Requested",
"Quote Requested",
]
)
.sum()
)
followups = int(
df.get(
"Next Action",
pd.Series(dtype=str),
)
.astype(str)
.str.contains(
"follow|retry|callback",
case=False,
na=False,
)
.sum()
)
human = int(
df.get(
"Human Intervention",
pd.Series(dtype=str),
)
.astype(str)
.str.lower()
.isin(
[
"yes",
"true",
]
)
.sum()
)
return total, hot, qualified, followups, human
def refresh_dashboard(df):
total, hot, qualified, followups, human = kpis(df)
return (
f"### {total}\nTotal Leads",
f"### {hot}\nπ₯ Hot Leads",
f"### {qualified}\nQualified",
f"### {followups}\nFollow-ups",
f"### {human}\nHuman Queue",
df,
)
# =========================================================
# LEAD IMPORT
# =========================================================
def upload_excel(file_obj):
if not file_obj:
df = build_demo_leads()
return (
df,
"No file selected. Demo data loaded.",
gr.update(
choices=df["Lead ID"].tolist(),
value=df.iloc[0]["Lead ID"],
),
)
try:
df = normalize_excel(file_obj)
msg = (
f"Loaded {len(df)} leads from Excel and mapped "
f"the sheet into the prototype lead model."
)
first = df.iloc[0]["Lead ID"] if len(df) else None
return (
df,
msg,
gr.update(
choices=df["Lead ID"].tolist(),
value=first,
),
)
except Exception as e:
df = build_demo_leads()
return (
df,
f"Could not map that workbook automatically: {e}. "
f"Demo data loaded instead.",
gr.update(
choices=df["Lead ID"].tolist(),
value=df.iloc[0]["Lead ID"],
),
)
# =========================================================
# ATTENDANCE & LEAD ALLOCATION
# =========================================================
def allocate(df, attendance, ai_first):
if df is None or df.empty:
return df, "No leads available."
present = attendance.loc[
attendance["Attendance"]
.astype(str)
.str.lower()
== "present",
"Employee",
].tolist()
result = assign_leads(
df.copy(),
present,
ai_first=ai_first,
)
mode = (
"AI-first qualification"
if ai_first
else "human round-robin"
)
return (
result,
f"Allocation completed using {mode}. "
f"Present staff: "
f"{', '.join(present) if present else 'None'}.",
)
# =========================================================
# LEAD HELPERS
# =========================================================
def get_lead(df, lead_id):
if df is None or df.empty or not lead_id:
return None
row = df[
df["Lead ID"].astype(str)
== str(lead_id)
]
if row.empty:
return None
return row.iloc[0].to_dict()
def lead_card(df, lead_id):
lead = get_lead(df, lead_id)
if not lead:
return "Select a lead."
return f"""
### {lead.get('Customer Name', 'Customer')} β {lead.get('Lead ID', '')}
**Phone:** {lead.get('Phone', '')}
**Location:** {lead.get('Location', '')}
**Requirement:** {lead.get('Requirement', '')}
**Current Status:** {lead.get('Status', 'New')}
**Assigned To:** {lead.get('Assigned To', 'AI Queue')}
**Priority:** {lead.get('Priority', 'Unscored')}
**Lead Score:** {lead.get('Lead Score', 0)}
"""
# =========================================================
# AI CALLING AGENT
# =========================================================
def demo_script(
df,
lead_id,
language,
scenario,
):
lead = get_lead(df, lead_id)
if not lead:
return "Select a lead first."
name = (
lead.get("Customer Name")
or "there"
)
requirement = (
lead.get("Requirement")
or "interior requirement"
)
intro = {
"English":
(
f"Hello {name}. "
f"Iβm the automated assistant from the interior design team. "
f"You recently submitted an enquiry regarding {requirement}. "
f"Is this a good time for a quick 2-minute discussion?"
),
"Kannada + English":
(
f"Hello {name}. "
f"Naanu interior design team-na automated assistant. "
f"Neevu recently {requirement} bagge enquiry submit maadidri. "
f"Iga 2 minutes maatadakke convenient-aa?"
),
"Hindi + English":
(
f"Hello {name}. "
f"Main interior design team ka automated assistant hoon. "
f"Aapne recently {requirement} ke liye enquiry submit ki thi. "
f"Kya abhi 2 minute baat karna convenient hai?"
),
}.get(
language,
"Hello. Iβm the automated assistant from the interior design team.",
)
prompts = {
"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."
),
"Site visit interest":
(
"Iβll quickly confirm your property details "
"and whether you would like our team to arrange a site visit."
),
"Catalogue request":
(
"Iβll understand your requirement and can arrange "
"for our catalogue and previous work references to be sent."
),
"No answer / callback":
(
"This scenario demonstrates a missed call or "
"callback request and automatic scheduling."
),
}
return (
intro
+ "\n\n"
+ prompts.get(
scenario,
prompts["Full qualification"],
)
)
def simulate_call(
df,
lead_id,
phone_override,
language,
scenario,
customer_reply,
):
lead = get_lead(
df,
lead_id,
)
if not lead:
return (
df,
"No lead selected.",
"",
"",
"",
gr.update(),
)
phone = (
phone_override
or lead.get("Phone")
or ""
).strip()
if not phone:
return (
df,
"Enter a controlled test phone number.",
"",
"",
"",
gr.update(),
)
call_result = VOICE.start_call(
phone=phone,
lead=lead,
scenario=scenario,
language=language,
customer_reply=customer_reply,
)
qualification = qualify_from_conversation(
lead,
call_result["transcript"],
scenario=scenario,
)
out = df.copy()
idx = out.index[
out["Lead ID"].astype(str)
== str(lead_id)
][0]
for key, value in qualification.items():
if key in out.columns:
out.at[idx, key] = value
out.at[
idx,
"Last Contact",
] = datetime.now().strftime(
"%Y-%m-%d %H:%M"
)
out.at[
idx,
"Call Result",
] = call_result["result"]
result_md = f"""
### β
AI Qualification Completed
**Call mode:** {call_result['mode']}
**Outcome:** {call_result['result']}
**Status:** {qualification['Status']}
**Priority:** {qualification['Priority']}
**Lead Score:** {qualification['Lead Score']}/100
**Next Action:** {qualification['Next Action']}
**Human Intervention:** {qualification['Human Intervention']}
"""
summary = qualification["AI Summary"]
wa = qualification.get(
"WhatsApp Action",
"No WhatsApp action required",
)
choices = out[
"Lead ID"
].tolist()
return (
out,
result_md,
call_result["transcript"],
summary,
wa,
gr.update(
choices=choices,
value=lead_id,
),
)
# =========================================================
# WHATSAPP AI ASSISTANT
# =========================================================
def whatsapp_lead_update(
df,
lead_id,
history,
customer_message,
):
"""
Simulate a WhatsApp Business conversation
while using the same lead engine.
"""
lead = get_lead(
df,
lead_id,
)
history = history or []
message = (
customer_message
or ""
).strip()
if not lead:
return (
df,
history,
"",
"Select a lead first.",
gr.update(),
)
if not message:
return (
df,
history,
"",
"Type a customer message.",
gr.update(),
)
previous_customer_text = " ".join(
str(
item.get(
"content",
"",
)
)
for item in history
if isinstance(
item,
dict,
)
and item.get(
"role"
)
== "user"
)
customer_context = (
previous_customer_text
+ " "
+ message
).strip()
qualification = qualify_from_conversation(
lead,
customer_context,
scenario="Full qualification",
)
lower = message.lower()
name = (
lead.get(
"Customer Name"
)
or "there"
)
if any(
x in lower
for x in [
"not interested",
"no requirement",
"don't need",
"do not need",
]
):
reply = (
f"Understood, {name}. "
f"Iβll close this enquiry for now. "
f"Thank you for your time."
)
elif any(
x in lower
for x in [
"site visit",
"visit my",
"visit the site",
"come and visit",
"someone to visit",
]
):
reply = (
"Certainly. Iβve marked this as a site-visit request. "
"Our human coordinator will confirm the available "
"date and time with you."
)
elif any(
x in lower
for x in [
"quotation",
"quote",
"estimate",
]
):
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."
)
elif any(
x in lower
for x in [
"catalog",
"catalogue",
"portfolio",
"previous work",
"images",
"photos",
"designs",
]
):
reply = (
"Absolutely. Iβve noted that you would like our "
"catalogue / previous-work references. "
"In production, the approved material would be "
"sent here automatically."
)
elif any(
x in lower
for x in [
"floor plan",
"floorplan",
]
):
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."
)
elif re.search(
r"\b\d+(?:\.\d+)?\s*(?:lakh|lac|lakhs|lacs)\b",
lower,
):
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?"
)
elif any(
x in lower
for x in [
"3bhk",
"3 bhk",
"2bhk",
"2 bhk",
"1bhk",
"1 bhk",
"villa",
"apartment",
"house",
]
):
reply = (
"Thanks, Iβve captured the property details. "
"Do you have an approximate budget, expected timeline, "
"or floor plan available?"
)
elif any(
x in lower
for x in [
"hello",
"hi",
"hey",
]
):
reply = (
f"Hello {name}! "
f"Iβm the AI assistant for the interior design team. "
f"I can help with your requirement, catalogue, "
f"floor plan, quotation, follow-up, or site-visit request. "
f"How can I help?"
)
else:
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?"
)
out = df.copy()
idx = out.index[
out["Lead ID"].astype(str)
== str(lead_id)
][0]
for key, value in qualification.items():
if key in out.columns:
out.at[
idx,
key,
] = value
out.at[
idx,
"Last Contact",
] = datetime.now().strftime(
"%Y-%m-%d %H:%M"
)
out.at[
idx,
"Call Result",
] = "WhatsApp prototype interaction"
new_history = history + [
{
"role": "user",
"content": message,
},
{
"role": "assistant",
"content": reply,
},
]
action_md = f"""
### AI Action
**Detected Status:** {qualification['Status']}
**Priority:** {qualification['Priority']}
**Lead Score:** {qualification['Lead Score']}/100
**Next Action:** {qualification['Next Action']}
**Human Intervention:** {qualification['Human Intervention']}
**Production channel:** WhatsApp Business API
**Prototype channel:** HF chat simulator
"""
return (
out,
new_history,
"",
action_md,
gr.update(
choices=out[
"Lead ID"
].tolist(),
value=lead_id,
),
)
def reset_whatsapp_chat(
df,
lead_id,
):
lead = get_lead(
df,
lead_id,
)
if not lead:
return (
[],
"Select a lead first.",
)
name = (
lead.get(
"Customer Name"
)
or "there"
)
req = (
lead.get(
"Requirement"
)
or "your interior requirement"
)
opening = (
f"Hello {name}! "
f"Iβm the AI assistant for the interior design team. "
f"Iβm following up on your enquiry about {req}. "
f"I can help with requirements, catalogue, floor plan, "
f"quotation, follow-up, or a site visit. "
f"How can I help?"
)
return (
[
{
"role": "assistant",
"content": opening,
}
],
"Conversation reset. Lead data is unchanged.",
)
# =========================================================
# HUMAN INTERVENTION
# =========================================================
def human_queue(df):
if df is None or df.empty:
return pd.DataFrame()
mask = (
df[
"Human Intervention"
]
.astype(str)
.str.lower()
.isin(
[
"yes",
"true",
]
)
)
cols = [
"Lead ID",
"Customer Name",
"Phone",
"Location",
"Requirement",
"Status",
"Priority",
"Lead Score",
"Next Action",
"AI Summary",
]
return (
df.loc[
mask,
[
c
for c in cols
if c in df.columns
],
]
.sort_values(
[
"Lead Score"
],
ascending=False,
)
)
# =========================================================
# OWNER REPORT
# =========================================================
def owner_report(df):
return generate_owner_summary(df)
# =========================================================
# PROCELEVATE BRAND CSS
# =========================================================
CSS = """
.gradio-container {
max-width: 1500px !important;
}
/* KPI Cards */
.kpi {
border: 1px solid #d9e1ea;
border-radius: 14px;
padding: 14px;
min-height: 95px;
background: white;
}
/* Procelevate Brand Header */
.hero {
background: #0F2C59 !important;
color: #FFFFFF !important;
padding: 22px;
border-radius: 18px;
margin-bottom: 12px;
}
/* Header Main Title */
.hero h1 {
color: #FFFFFF !important;
margin: 0 !important;
font-weight: 700;
}
/* Header Subtitle */
.hero p {
color: #FFFFFF !important;
margin: 7px 0 0 !important;
opacity: 1 !important;
}
/* Small Notes */
.small-note {
font-size: 12px;
opacity: .8;
}
"""
# =========================================================
# GRADIO APPLICATION
# =========================================================
with gr.Blocks(
title=APP_TITLE,
css=CSS,
theme=gr.themes.Soft(),
) as demo:
leads_state = gr.State(
load_initial_leads()
)
# -----------------------------------------------------
# PROCELEVATE HERO HEADER
# -----------------------------------------------------
gr.HTML(
"""
<div class="hero">
<h1>
AI-Powered Lead Conversion & Customer Engagement
</h1>
<p>
Interior Business β’
Meta Lead β
AI Qualification β
Status β
WhatsApp Action β
Human Handoff
</p>
</div>
"""
)
# =====================================================
# DASHBOARD
# =====================================================
with gr.Tab(
"π Dashboard"
):
with gr.Row():
k1 = gr.Markdown(
elem_classes="kpi"
)
k2 = gr.Markdown(
elem_classes="kpi"
)
k3 = gr.Markdown(
elem_classes="kpi"
)
k4 = gr.Markdown(
elem_classes="kpi"
)
k5 = gr.Markdown(
elem_classes="kpi"
)
dashboard_table = gr.Dataframe(
interactive=False,
wrap=True,
label="Lead Pipeline",
)
refresh_btn = gr.Button(
"Refresh Dashboard",
variant="primary",
)
# =====================================================
# LEAD IMPORT
# =====================================================
with gr.Tab(
"π₯ Lead Import"
):
gr.Markdown(
"""
Upload the client's Excel sheet.
The prototype maps the incoming Facebook / Instagram lead data
into the AI lead-management workflow.
"""
)
excel_file = gr.File(
label="Upload Excel (.xlsx/.xls)",
file_types=[
".xlsx",
".xls",
],
type="filepath",
)
import_btn = gr.Button(
"Load Leads",
variant="primary",
)
import_msg = gr.Markdown()
imported_table = gr.Dataframe(
interactive=False,
wrap=True,
)
# =====================================================
# ATTENDANCE & ALLOCATION
# =====================================================
with gr.Tab(
"π₯ Attendance & Allocation"
):
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.
"""
)
attendance = gr.Dataframe(
value=empty_attendance(),
headers=[
"Employee",
"Attendance",
],
datatype=[
"str",
"str",
],
interactive=True,
label="Today's Attendance",
)
ai_first = gr.Checkbox(
value=True,
label="AI-first qualification mode",
)
allocate_btn = gr.Button(
"Allocate Today's Leads",
variant="primary",
)
allocation_msg = gr.Markdown()
allocation_table = gr.Dataframe(
interactive=False,
wrap=True,
)
# =====================================================
# AI CALLING AGENT
# =====================================================
with gr.Tab(
"π AI Calling Agent"
):
gr.Markdown(
"""
For this HF prototype, the conversation and call outcome
are simulated.
The production solution can connect the same workflow
to a real Voice AI / telephony provider.
"""
)
with gr.Row():
lead_selector = gr.Dropdown(
choices=load_initial_leads()[
"Lead ID"
].tolist(),
value=load_initial_leads()
.iloc[0]["Lead ID"],
label="Lead",
)
phone_override = gr.Textbox(
label="Controlled Test Phone Number",
placeholder=(
"Enter your business number "
"for later live-call integration"
),
)
language = gr.Dropdown(
[
"English",
"Kannada + English",
"Hindi + English",
],
value="English",
label="Conversation Language",
)
scenario = gr.Dropdown(
[
"Full qualification",
"Site visit interest",
"Catalogue request",
"No answer / callback",
],
value="Full qualification",
label="Demo Scenario",
)
selected_card = gr.Markdown()
generate_script_btn = gr.Button(
"Generate AI Opening"
)
ai_opening = gr.Textbox(
label="AI Opening / Conversation Goal",
lines=5,
)
customer_reply = gr.Textbox(
label=(
"Your Demo Reply "
"(act as the customer)"
),
lines=7,
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."
),
)
call_btn = gr.Button(
"π€ Run AI Qualification Call",
variant="primary",
)
call_result_md = gr.Markdown()
with gr.Row():
transcript = gr.Textbox(
label="Call Transcript",
lines=12,
)
ai_summary = gr.Textbox(
label="AI Call Summary",
lines=12,
)
whatsapp_action = gr.Textbox(
label=(
"Automatic WhatsApp / "
"Workflow Action"
),
lines=4,
)
# =====================================================
# WHATSAPP AI ASSISTANT
# =====================================================
with gr.Tab(
"π¬ WhatsApp AI Assistant"
):
gr.Markdown(
"""
### WhatsApp-style AI conversation prototype
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.
**No WhatsApp API is used in this prototype.**
After project approval, the same workflow can be connected
to WhatsApp Business.
"""
)
with gr.Row():
wa_lead_selector = gr.Dropdown(
choices=load_initial_leads()[
"Lead ID"
].tolist(),
value=load_initial_leads()
.iloc[0]["Lead ID"],
label="Customer Lead",
)
wa_reset_btn = gr.Button(
"Start / Reset Conversation"
)
wa_lead_card = gr.Markdown()
wa_chat = gr.Chatbot(
label="Customer β AI Assistant",
type="messages",
height=420,
)
with gr.Row():
wa_customer_message = gr.Textbox(
label="Type as the customer",
placeholder=(
"Example: Please send your catalogue. "
"I have a 3BHK and would like a site visit."
),
lines=3,
scale=5,
)
wa_send_btn = gr.Button(
"Send Message",
variant="primary",
scale=1,
)
wa_action_panel = gr.Markdown()
gr.Examples(
examples=[
[
"Please send me your catalogue "
"and previous work images."
],
[
"I have a 3BHK apartment and "
"my budget is around 12 lakh."
],
[
"I have the floor plan. "
"How can I share it?"
],
[
"Can someone visit my apartment "
"this Saturday?"
],
[
"Please prepare a quotation for me."
],
[
"I am not interested anymore."
],
],
inputs=[
wa_customer_message
],
label="Demo customer messages",
)
# =====================================================
# HUMAN INTERVENTION
# =====================================================
with gr.Tab(
"π€ Human Intervention"
):
human_btn = gr.Button(
"Refresh Human Queue",
variant="primary",
)
human_table = gr.Dataframe(
interactive=False,
wrap=True,
label=(
"Leads requiring "
"the remaining employee"
),
)
# =====================================================
# OWNER DAILY REPORT
# =====================================================
with gr.Tab(
"π Owner AI Daily Report"
):
report_btn = gr.Button(
"Generate Daily AI Summary",
variant="primary",
)
report = gr.Markdown()
# =====================================================
# PROTOTYPE SCOPE
# =====================================================
with gr.Tab(
"βοΈ Prototype Scope"
):
gr.Markdown(
"""
### What is real in this HF prototype
- Excel lead upload and normalization
- Attendance and assignment workflow
- AI-first lead queue concept
- Conversation-based lead qualification
- WhatsApp-style AI customer chat
- Automatic lead updates
- Lead scoring
- Lead status classification
- AI summary
- Next-action generation
- Human-intervention queue
- Owner summary
- Automatic dashboard refresh
### What is intentionally simulated in the prototype
- Actual outbound PSTN / phone call
- Meta lead webhook / live Meta API
- WhatsApp Business message delivery
- Live quotation sending
- Calendar scheduling
- Site-visit calendar blocking
- Automated production reminders
The production solution can connect these APIs
without changing the core lead-management workflow.
"""
)
# =====================================================
# EVENTS
# =====================================================
refresh_btn.click(
refresh_dashboard,
inputs=[
leads_state
],
outputs=[
k1,
k2,
k3,
k4,
k5,
dashboard_table,
],
)
# ---------------- LEAD IMPORT ----------------
import_event = import_btn.click(
upload_excel,
inputs=[
excel_file
],
outputs=[
leads_state,
import_msg,
lead_selector,
],
)
import_event.then(
lambda x: x,
inputs=[
leads_state
],
outputs=[
imported_table
],
).then(
lambda df: gr.update(
choices=df[
"Lead ID"
].tolist(),
value=(
df.iloc[0][
"Lead ID"
]
if len(df)
else None
),
),
inputs=[
leads_state
],
outputs=[
wa_lead_selector
],
)
# ---------------- ALLOCATION ----------------
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
],
)
# ---------------- AI CALLING ----------------
lead_selector.change(
lead_card,
inputs=[
leads_state,
lead_selector,
],
outputs=[
selected_card
],
)
generate_script_btn.click(
demo_script,
inputs=[
leads_state,
lead_selector,
language,
scenario,
],
outputs=[
ai_opening
],
)
call_event = 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,
],
)
# Refresh dashboard automatically after AI call
call_event.then(
refresh_dashboard,
inputs=[
leads_state
],
outputs=[
k1,
k2,
k3,
k4,
k5,
dashboard_table,
],
).then(
lead_card,
inputs=[
leads_state,
lead_selector,
],
outputs=[
selected_card
],
).then(
human_queue,
inputs=[
leads_state
],
outputs=[
human_table
],
)
# ---------------- WHATSAPP ----------------
wa_lead_selector.change(
lead_card,
inputs=[
leads_state,
wa_lead_selector,
],
outputs=[
wa_lead_card
],
)
wa_reset_btn.click(
reset_whatsapp_chat,
inputs=[
leads_state,
wa_lead_selector,
],
outputs=[
wa_chat,
wa_action_panel,
],
)
wa_event = wa_send_btn.click(
whatsapp_lead_update,
inputs=[
leads_state,
wa_lead_selector,
wa_chat,
wa_customer_message,
],
outputs=[
leads_state,
wa_chat,
wa_customer_message,
wa_action_panel,
wa_lead_selector,
],
)
wa_event.then(
refresh_dashboard,
inputs=[
leads_state
],
outputs=[
k1,
k2,
k3,
k4,
k5,
dashboard_table,
],
).then(
lead_card,
inputs=[
leads_state,
wa_lead_selector,
],
outputs=[
wa_lead_card
],
).then(
human_queue,
inputs=[
leads_state
],
outputs=[
human_table
],
)
# ---------------- HUMAN QUEUE ----------------
human_btn.click(
human_queue,
inputs=[
leads_state
],
outputs=[
human_table
],
)
# ---------------- OWNER REPORT ----------------
report_btn.click(
owner_report,
inputs=[
leads_state
],
outputs=[
report
],
)
# =====================================================
# INITIAL LOAD
# =====================================================
demo.load(
refresh_dashboard,
inputs=[
leads_state
],
outputs=[
k1,
k2,
k3,
k4,
k5,
dashboard_table,
],
)
demo.load(
lead_card,
inputs=[
leads_state,
lead_selector,
],
outputs=[
selected_card
],
)
demo.load(
lead_card,
inputs=[
leads_state,
wa_lead_selector,
],
outputs=[
wa_lead_card
],
)
# =========================================================
# RUN APPLICATION
# =========================================================
if __name__ == "__main__":
demo.launch()
import os
import re
import json
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Tuple
import gradio as gr
import pandas as pd
from services.lead_logic import (
normalize_excel,
build_demo_leads,
assign_leads,
qualify_from_conversation,
generate_owner_summary,
)
from services.voice_service import VoiceService
APP_TITLE = "AI Lead Conversion Prototype | Interior Business"
DATA_DIR = Path("data")
DATA_DIR.mkdir(exist_ok=True)
VOICE = VoiceService()
STAFF = [
"Employee 1",
"Employee 2",
"Employee 3",
"Employee 4",
]
# =========================================================
# BASIC DATA FUNCTIONS
# =========================================================
def empty_attendance():
return pd.DataFrame(
{
"Employee": STAFF,
"Attendance": [
"Present",
"Present",
"Present",
"Present",
],
}
)
def load_initial_leads():
return build_demo_leads()
def kpis(df: pd.DataFrame):
if df is None or df.empty:
return 0, 0, 0, 0, 0
total = len(df)
hot = int(
(
df.get(
"Priority",
pd.Series(dtype=str),
)
== "HOT"
).sum()
)
qualified = int(
df.get(
"Status",
pd.Series(dtype=str),
)
.isin(
[
"Qualified",
"Site Visit Requested",
"Quote Requested",
]
)
.sum()
)
followups = int(
df.get(
"Next Action",
pd.Series(dtype=str),
)
.astype(str)
.str.contains(
"follow|retry|callback",
case=False,
na=False,
)