Update app.py
Browse files8 unmodified lines9101112131415161718197 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071721 unmodified line747576777879803 unmodified lines848586878889901 unmodified line929394959697981 unmodified line1001011021031041051061071081091103 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391 unmodified line1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901915 unmodified lines1971981992002012022035 unmodified lines20921021121221321421513 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512523 unmodified lines2562572582592602612622632642652662672682692702712728 unmodified linesfaq_df = pd.read_csv("lic_faq.csv", encoding="ISO-8859-1")# Initialize the SentenceTransformer model for semantic text similarity# 'all-MiniLM-L6-v2' is a lightweight model for encoding text into embeddingsmodel = SentenceTransformer('all-MiniLM-L6-v2')# Convert FAQ questions into embeddings for similarity comparison# This allows the chatbot to match user queries to the closest FAQ questionfaq_embeddings = model.encode(faq_df['question'].tolist(), convert_to_tensor=True)# Define policy suggestions to recommend based on keywords in the user query7 unmodified lines# Chatbot function to process user queries and generate responsesdef chatbot(history, query):# Convert query to lowercase and strip whitespace for consistent processingquery_lower = query.lower().strip()# Handle common greetings with a friendly responseif 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:# Encode the user query into an embedding for similarity comparisonquery_embedding = model.encode(query, convert_to_tensor=True)# Calculate cosine similarity between the query and FAQ embeddingsscores = util.pytorch_cos_sim(query_embedding, faq_embeddings)[0]# Find the highest similarity score and its corresponding FAQ indexbest_score = float(scores.max())best_idx = int(scores.argmax())# If the similarity score is below 0.6, return a fallback response# This ensures only confident matches are usedif 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:# Retrieve the answer from the FAQ datasetresponse = faq_df.iloc[best_idx]['answer']# Add policy suggestion if the query contains a relevant keywordfor keyword, suggestion in policy_suggestions.items():if keyword in query_lower:response += f"\n\n{suggestion}"break# Append the query and response to the chat historyhistory.append((query, response))# Return updated history for both the chatbot UI and statereturn history, history# Custom CSS for a modern, dynamic UIcustom_css = """/* General container styling: Set a gradient background and modern font */.gradio-container {font-family: 'Segoe UI', Arial, sans-serif;background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);1 unmodified linepadding: 20px;}/* Header styling: Centered, bold, with animation for a smooth entrance */h1 {color: #0D47A1 !important;font-size: 2.5em !important;3 unmodified linesanimation: fadeInDown 1s ease-in-out;}/* Paragraph styling: Centered, slightly smaller text for the subtitle */p {color: #1565C0 !important;font-size: 1.2em !important;1 unmodified linemargin-bottom: 20px;}/* Chatbot container: Rounded, shadowed, and centered with scrollable content */.chatbot {border-radius: 15px !important;box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;1 unmodified linepadding: 15px !important;max-width: 800px !important;margin: 0 auto !important;height: 500px !important;overflow-y: auto !important;}/* Chat bubbles: Rounded, animated, with hover effect for interactivity */.chatbot .bubble {border-radius: 15px !important;padding: 12px 18px !important;3 unmodified linestransition: transform 0.2s ease;}/* Hover effect for chat bubbles: Slightly scale up for a dynamic feel */.chatbot .bubble:hover {transform: scale(1.02);}/* User bubble: Blue background, right-aligned for user messages */.chatbot .bubble:nth-child(odd) {background: #0D47A1 !important;color: white !important;margin-left: auto !important;}/* Bot bubble: Light blue background, left-aligned for bot responses */.chatbot .bubble:nth-child(even) {background: #E3F2FD !important;color: #1E1E1E !important;margin-right: auto !important;}/* Textbox styling: Rounded, shadowed, with focus effects for better UX */input[type="text"] {border: 2px solid #0D47A1 !important;border-radius: 25px !important;1 unmodified linefont-size: 1em !important;box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;transition: border-color 0.3s ease, box-shadow 0.3s ease;}/* Textbox focus: Highlight border and shadow when typing */input[type="text"]:focus {border-color: #1565C0 !important;box-shadow: 0 4px 12px rgba(21, 101, 192, 0.3) !important;outline: none !important;}/* Button styling: Rounded, shadowed, with hover and active effects */button {border-radius: 25px !important;background: #0D47A1 !important;color: white !important;padding: 12px 24px !important;font-size: 1em !important;border: none !important;box-shadow: 0 2px 8px rgba(0,0,0,0.2) !important;transition: background 0.3s ease, transform 0.2s ease !important;}/* Button hover: Change color and lift slightly for a dynamic effect */button:hover {background: #1565C0 !important;transform: translateY(-2px) !important;}/* Button active: Reset lift when clicked */button:active {transform: translateY(0) !important;}/* Clear button: Different color, centered for accessibility */button[aria-label="Clear Chat"] {background: #B0BEC5 !important;margin: 10px auto !important;display: block !important;}/* Clear button hover: Slightly darker for feedback */button[aria-label="Clear Chat"]:hover {background: #90A4AE !important;}/* Fade-in animation for header */@keyframes fadeInDown {from {opacity: 0;5 unmodified lines}}/* Slide-in animation for chat bubbles */@keyframes slideIn {from {opacity: 0;5 unmodified lines}}/* Scrollbar styling: Sleek, modern look for the chatbot container */.chatbot::-webkit-scrollbar {width: 8px;}13 unmodified lines}"""# Create the Gradio interface with custom stylingwith gr.Blocks(title="LIC Agent Chatbot", css=custom_css) as demo:# Display a header with title and subtitlegr.Markdown("<h1>🧑💼 LIC Agent Assistant</h1>""<p>Ask me anything about policies, claims, commissions, onboarding, and KYC.</p>")# Chatbot UI component with custom height, avatars, and copy buttonchatbot_ui = gr.Chatbot(label="LIC Assistant",height=500,bubble_full_width=False,avatar_images=("🧑", "🤖"),show_copy_button=True)# Create a row for the input textbox and send buttonwith gr.Row():msg = gr.Textbox(placeholder="Type your question here...",3 unmodified lines)send = gr.Button("Send", variant="primary", scale=2)# Clear button to reset the chatclear = gr.Button("Clear Chat", variant="secondary")# State to store chat historystate = gr.State([])# Link the send button to the chatbot functionsend.click(fn=chatbot, inputs=[state, msg], outputs=[chatbot_ui, state])# Link the clear button to reset the chat history and UIclear.click(lambda: ([], []), None, [chatbot_ui, state], queue=False)# Launch the Gradio appdemo.launch()8 unmodified lines910111213141516177 unmodified lines2526272829303132333435363738394041424344454647484950515253545556571 unmodified line596061626364653 unmodified lines6970717273741 unmodified line767778798081821 unmodified line848586878889909192939495969798991001011021033 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291 unmodified line1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811825 unmodified lines1881891901911921935 unmodified lines19920020120220320420513 unmodified lines2192202212222232242252262272282292302312322332342352362372383 unmodified lines2422432442452462472482492502512522532542552562572582592608 unmodified linesfaq_df = pd.read_csv("lic_faq.csv", encoding="ISO-8859-1")# Initialize the SentenceTransformer model for semantic text similaritymodel = SentenceTransformer('all-MiniLM-L6-v2')# Convert FAQ questions into embeddings for similarity comparisonfaq_embeddings = model.encode(faq_df['question'].tolist(), convert_to_tensor=True)# Define policy suggestions to recommend based on keywords in the user query7 unmodified lines# Chatbot function to process user queries and generate responsesdef chatbot(history, query):query_lower = query.lower().strip()# Handle common greetings with a friendly responseif 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}"breakhistory.append((query, response))return history, history# Custom CSS for a modern, dynamic UI with mobile responsivenesscustom_css = """/* General container styling */.gradio-container {font-family: 'Segoe UI', Arial, sans-serif;background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);1 unmodified linepadding: 20px;}/* Header styling */h1 {color: #0D47A1 !important;font-size: 2.5em !important;3 unmodified linesanimation: fadeInDown 1s ease-in-out;}p {color: #1565C0 !important;font-size: 1.2em !important;1 unmodified linemargin-bottom: 20px;}/* Chatbot container: Adjusted size and responsive design */.chatbot {border-radius: 15px !important;box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;1 unmodified linepadding: 15px !important;max-width: 800px !important;margin: 0 auto !important;height: 600px !important; /* Increased chat window height */overflow-y: auto !important;}/* Mobile adjustments for chat window */@media (max-width: 768px) {.chatbot {max-width: 100% !important;height: 400px !important; /* Reduced height for mobile */margin: 0 !important;}}/* Chat bubbles */.chatbot .bubble {border-radius: 15px !important;padding: 12px 18px !important;3 unmodified linestransition: transform 0.2s ease;}.chatbot .bubble:hover {transform: scale(1.02);}.chatbot .bubble:nth-child(odd) {background: #0D47A1 !important;color: white !important;margin-left: auto !important;}.chatbot .bubble:nth-child(even) {background: #E3F2FD !important;color: #1E1E1E !important;margin-right: auto !important;}/* Textbox styling */input[type="text"] {border: 2px solid #0D47A1 !important;border-radius: 25px !important;1 unmodified linefont-size: 1em !important;box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;transition: border-color 0.3s ease, box-shadow 0.3s ease;flex-grow: 1 !important;}input[type="text"]:focus {border-color: #1565C0 !important;box-shadow: 0 4px 12px rgba(21, 101, 192, 0.3) !important;outline: none !important;}/* Button styling: Larger Send button */button {border-radius: 25px !important;background: #0D47A1 !important;color: white !important;padding: 15px 30px !important; /* Increased padding for larger size */font-size: 1em !important;border: none !important;box-shadow: 0 2px 8px rgba(0,0,0,0.2) !important;transition: background 0.3s ease, transform 0.2s ease !important;min-width: 120px !important; /* Minimum width for Send button */}button:hover {background: #1565C0 !important;transform: translateY(-2px) !important;}button:active {transform: translateY(0) !important;}/* Clear button: Reduced size */button[aria-label="Clear Chat"] {background: #B0BEC5 !important;margin: 10px auto !important;display: block !important;padding: 8px 20px !important; /* Reduced padding */font-size: 0.9em !important;min-width: 100px !important; /* Reduced width */}button[aria-label="Clear Chat"]:hover {background: #90A4AE !important;}/* Animations */@keyframes fadeInDown {from {opacity: 0;5 unmodified lines}}@keyframes slideIn {from {opacity: 0;5 unmodified lines}}/* Scrollbar styling */.chatbot::-webkit-scrollbar {width: 8px;}13 unmodified lines}"""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, # Increased default heightbubble_full_width=False,avatar_images=("🧑", "🤖"),show_copy_button=True)with gr.Row():msg = gr.Textbox(placeholder="Type your question here...",3 unmodified lines)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 textboxdef send_message(history, query):if query:history, _ = chatbot(history, query)return history, ""return history, querysend.click(fn=send_message, inputs=[state, msg], outputs=[chatbot_ui, msg])msg.submit(fn=send_message, inputs=[state, msg], outputs=[chatbot_ui, msg]) # Add Enter key supportclear.click(lambda: ([], []), None, [chatbot_ui, state], queue=False)demo.launch()
app.py+36-48