import gradio as gr import joblib from src.preprocess import clean_text import time import datetime # Load model and responses model = joblib.load("models/lms_chatbot.joblib") responses = joblib.load("models/responses.joblib") # Keep conversation history history = [] def chatbot_response(user_input): """Generates chat HTML with typing animation for bot.""" if not user_input.strip(): return "" # User message timestamp = datetime.datetime.now().strftime("%H:%M") history.append({ "sender": "You", "message": user_input, "time": timestamp, "color": "#DCF8C6", "align": "right" }) # Bot typing animation bot_reply = responses.get(model.predict([clean_text(user_input)])[0], ["Sorry, I don't understand."])[0] typing_html = """
Bot is typing...
""" # Render chat with typing bubble chat_html = render_chat(typing=True) # Simulate typing for i in range(len(bot_reply)+1): history.append({ "sender": "Bot", "message": bot_reply[:i], "time": timestamp, "color": "#FFFFFF", "align": "left" }) chat_html = render_chat() time.sleep(0.03) history.pop() # remove last partial message to update in next loop # Add final bot message history.append({ "sender": "Bot", "message": bot_reply, "time": timestamp, "color": "#FFFFFF", "align": "left" }) return render_chat() def render_chat(typing=False): chat_html = """
""" for msg in history: chat_html += f"""
{msg['message']}
{msg['time']}
""" if typing: chat_html += """
Bot is typing...
""" chat_html += "
" return chat_html # Gradio interface demo = gr.Interface( fn=chatbot_response, inputs=gr.Textbox(lines=2, placeholder="Type your message here...", label="Your Message"), outputs=gr.HTML(label="Chat"), title="🟢 LMS Chatbot", description="Ask anything about your LMS. Automatic reply with typing animation!" ) if __name__ == "__main__": demo.launch()