LIC_Agent / app.py
dschandra's picture
Update app.py
5d0c81e verified
raw
history blame
8.03 kB
import gradio as gr
import pandas as pd
from sentence_transformers import SentenceTransformer, util
# Load FAQ data from a CSV file containing questions and answers
try:
faq_df = pd.read_csv("lic_faq.csv", encoding="utf-8")
except UnicodeDecodeError:
faq_df = pd.read_csv("lic_faq.csv", encoding="ISO-8859-1")
# Initialize the SentenceTransformer model for semantic text similarity
model = SentenceTransformer('all-MiniLM-L6-v2')
# Convert FAQ questions into embeddings for similarity comparison
faq_embeddings = model.encode(faq_df['question'].tolist(), convert_to_tensor=True)
# Define policy suggestions to recommend based on keywords in the user query
policy_suggestions = {
"term": "πŸ’‘ You might consider LIC Tech Term Plan for pure protection at low cost.",
"money back": "πŸ’‘ LIC Money Back Policy is great for periodic returns along with insurance.",
"endowment": "πŸ’‘ LIC New Endowment Plan offers savings and insurance benefits together.",
"ulip": "πŸ’‘ LIC SIIP and Nivesh Plus are good ULIP options with market-linked returns.",
"pension": "πŸ’‘ LIC Jeevan Akshay and PM Vaya Vandana Yojana are best for pension seekers."
}
# Chatbot function to process user queries and generate responses
def chatbot(history, query):
query_lower = query.lower().strip()
# Handle common greetings with a friendly response
if query_lower in ["hi", "hello", "hey", "good morning", "good evening"]:
response = "πŸ‘‹ Hello! I’m your LIC Assistant. Ask me anything about policies, claims, onboarding, or commission."
else:
query_embedding = model.encode(query, convert_to_tensor=True)
scores = util.pytorch_cos_sim(query_embedding, faq_embeddings)[0]
best_score = float(scores.max())
best_idx = int(scores.argmax())
if best_score < 0.6:
response = "πŸ€– I'm not confident I have the right answer for that. Please ask about LIC policies, claims, commissions, onboarding, or KYC."
else:
response = faq_df.iloc[best_idx]['answer']
for keyword, suggestion in policy_suggestions.items():
if keyword in query_lower:
response += f"\n\n{suggestion}"
break
history.append((query, response))
return history, history
# Custom CSS for a normal chatbot visual design
custom_css = """
/* General container styling */
.gradio-container {
font-family: 'Arial', sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); /* Neutral gradient */
min-height: 100vh;
padding: 0;
margin: 0;
font-size: 14px; /* Base font size */
}
/* Header styling */
h1 {
color: #2c3e50 !important; /* Dark blue for professionalism */
font-size: 24px !important;
text-align: center;
margin: 15px 0;
text-shadow: none;
}
p {
color: #34495e !important; /* Slightly lighter blue */
font-size: 14px !important;
text-align: center;
margin-bottom: 15px;
}
/* Chatbot container */
.chatbot {
border-radius: 8px !important;
box-shadow: 0 2px 10px rgba(0,0,0,0.1) !important;
background: #ffffff !important;
padding: 10px !important;
max-width: 800px !important;
margin: 0 auto !important;
height: 70vh !important; /* Adjusted for normal view */
overflow-y: auto !important;
display: block; /* Reset to default flow */
}
/* Chat bubbles: Normal design */
.chatbot .bubble {
border-radius: 8px !important;
padding: 8px 12px !important;
margin: 5px 0 !important;
max-width: 70% !important;
font-size: 14px !important; /* Normal text size */
min-height: 30px !important; /* Controlled minimum height */
min-width: 60px !important; /* Controlled minimum width */
word-wrap: break-word !important;
line-height: 1.4 !important; /* Readable line spacing */
color: #2c3e50 !important; /* Consistent text color */
}
/* User bubble: Right-aligned, light blue */
.chatbot .bubble:nth-child(odd) {
background: #3498db !important; /* Light blue for user */
color: #ffffff !important; /* White text for contrast */
margin-left: auto !important;
align-self: flex-end !important;
}
/* Bot bubble: Left-aligned, light gray */
.chatbot .bubble:nth-child(even) {
background: #ecf0f1 !important; /* Light gray for bot */
margin-right: auto !important;
align-self: flex-start !important;
}
/* Input area */
.gradio-row:last-child {
width: 100% !important;
max-width: 800px !important;
margin: 10px auto !important;
padding: 10px !important;
display: flex !important;
align-items: center !important;
background: transparent !important;
}
/* Textbox styling */
input[type="text"] {
border: 1px solid #bdc3c7 !important;
border-radius: 4px !important;
padding: 8px 12px !important;
font-size: 14px !important;
box-shadow: 0 1px 3px rgba(0,0,0,0.1) !important;
flex-grow: 1 !important;
margin-right: 10px !important;
color: #2c3e50 !important;
}
input[type="text"]::placeholder {
color: #7f8c8d !important; /* Gray placeholder */
font-size: 14px !important;
}
input[type="text"]:focus {
border-color: #3498db !important;
outline: none !important;
}
/* Send button */
button {
border-radius: 4px !important;
background: #3498db !important; /* Matching user bubble */
color: white !important;
padding: 8px 20px !important;
font-size: 14px !important;
border: none !important;
min-width: 80px !important;
transition: background 0.3s ease !important;
text-align: center !important;
}
button:hover {
background: #2980b9 !important;
}
/* Clear button */
button[aria-label="Clear Chat"] {
background: #bdc3c7 !important; /* Silver gray */
padding: 6px 15px !important;
font-size: 14px !important;
min-width: 90px !important;
margin-top: 10px !important;
align-self: center !important;
color: #ffffff !important;
}
button[aria-label="Clear Chat"]:hover {
background: #95a5a6 !important;
}
/* Scrollbar styling */
.chatbot::-webkit-scrollbar {
width: 6px;
}
.chatbot::-webkit-scrollbar-track {
background: #f5f7fa;
}
.chatbot::-webkit-scrollbar-thumb {
background: #3498db;
border-radius: 3px;
}
.chatbot::-webkit-scrollbar-thumb:hover {
background: #2980b9;
}
/* Mobile-specific adjustments */
@media (max-width: 768px) {
.chatbot {
max-width: 100% !important;
height: 65vh !important; /* Adjusted for mobile */
margin: 0 !important;
}
.gradio-row:last-child {
max-width: 100% !important;
padding: 5px !important;
}
input[type="text"] {
padding: 6px 10px !important;
}
button {
padding: 6px 15px !important;
}
}
"""
with gr.Blocks(title="LIC Agent Chatbot", css=custom_css) as demo:
gr.Markdown(
"<h1>πŸ§‘β€πŸ’Ό LIC Agent Assistant</h1>"
"<p>Ask me anything about policies, claims, commissions, onboarding, and KYC.</p>"
)
chatbot_ui = gr.Chatbot(
label="LIC Assistant",
height=600,
bubble_full_width=False,
avatar_images=("πŸ§‘", "πŸ€–"),
show_copy_button=True
)
with gr.Row():
msg = gr.Textbox(
placeholder="Type your question here...",
show_label=False,
scale=8,
elem_classes="chat-input"
)
send = gr.Button("Send", variant="primary", scale=2)
clear = gr.Button("Clear Chat", variant="secondary")
state = gr.State([])
# Send message on Enter key and clear textbox
def send_message(history, query):
if query:
history, _ = chatbot(history, query)
return history, ""
return history, query
send.click(fn=send_message, inputs=[state, msg], outputs=[chatbot_ui, msg])
msg.submit(fn=send_message, inputs=[state, msg], outputs=[chatbot_ui, msg])
clear.click(lambda: ([], []), None, [chatbot_ui, state], queue=False)
demo.launch()