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( """
Interior Business • Meta Lead → AI Qualification → Status → WhatsApp Action → Human Handoff