Spaces:
No application file
No application file
| The user is asking for a chatbot application. This is a relatively simple request that would work well as a single-file Streamlit application. I should create a complete, working chatbot with: | |
| 1. A chat interface | |
| 2. Message history | |
| 3. User input for messages | |
| 4. A backend to handle responses (I'll use a simple rule-based bot for now, but could be extensible) | |
| 5. Nice UI with Streamlit components | |
| 6. Session state to maintain chat history | |
| 7. Clear chat functionality | |
| This is simple enough that I can do it as a single file application, but I should still generate a requirements.txt file for the dependencies. | |
| Let me create a complete chatbot application with a clean, modern interface. | |
| I'll create a complete chatbot application for you with a modern, interactive interface. Let me build this as a single-file Streamlit app with proper chat functionality. | |
| === streamlit_app.py === | |
| import streamlit as st | |
| import time | |
| import random | |
| from datetime import datetime | |
| import json | |
| # Configure the page | |
| st.set_page_config( | |
| page_title="AI Chatbot", | |
| page_icon="π€", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Custom CSS for better styling | |
| st.markdown(""" | |
| <style> | |
| .chat-container { | |
| max-width: 800px; | |
| margin: 0 auto; | |
| } | |
| .user-message { | |
| background-color: #e3f2fd; | |
| padding: 10px 15px; | |
| border-radius: 10px 10px 3px 10px; | |
| margin: 5px 0; | |
| text-align: right; | |
| } | |
| .bot-message { | |
| background-color: #f5f5f5; | |
| padding: 10px 15px; | |
| border-radius: 10px 10px 10px 3px; | |
| margin: 5px 0; | |
| text-align: left; | |
| } | |
| .message-timestamp { | |
| font-size: 0.8em; | |
| color: #666; | |
| margin-top: 5px; | |
| } | |
| .chat-header { | |
| text-align: center; | |
| padding: 20px; | |
| background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); | |
| color: white; | |
| border-radius: 10px; | |
| margin-bottom: 20px; | |
| } | |
| .sidebar-info { | |
| background-color: #f0f2f6; | |
| padding: 15px; | |
| border-radius: 10px; | |
| margin-bottom: 20px; | |
| } | |
| .typing-indicator { | |
| background-color: #f5f5f5; | |
| padding: 10px 15px; | |
| border-radius: 10px 10px 10px 3px; | |
| margin: 5px 0; | |
| text-align: left; | |
| font-style: italic; | |
| color: #666; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # Initialize session state | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| if "chat_id" not in st.session_state: | |
| st.session_state.chat_id = str(int(time.time())) | |
| if "user_name" not in st.session_state: | |
| st.session_state.user_name = "User" | |
| # Bot responses database | |
| BOT_RESPONSES = { | |
| "greetings": [ | |
| "Hello! How can I help you today?", | |
| "Hi there! What's on your mind?", | |
| "Hey! Great to see you. How are you doing?", | |
| "Hello! I'm here to chat. What would you like to talk about?" | |
| ], | |
| "goodbyes": [ | |
| "Goodbye! It was nice talking with you!", | |
| "See you later! Take care!", | |
| "Bye! Hope to chat again soon!", | |
| "Farewell! Have a wonderful day!" | |
| ], | |
| "how_are_you": [ | |
| "I'm doing great, thank you for asking! How are you?", | |
| "I'm doing well! I hope you're having a good day too!", | |
| "I'm fantastic! Always excited to chat. How about you?", | |
| "I'm doing good! Ready to help with whatever you need." | |
| ], | |
| "questions": [ | |
| "That's an interesting question! Let me think about that...", | |
| "Hmm, that's something worth exploring. What do you think?", | |
| "Great question! I'd love to hear your perspective on this.", | |
| "I'm curious about your thoughts on that too!" | |
| ], | |
| "compliments": [ | |
| "Thank you! That's very kind of you to say!", | |
| "Aww, you're too sweet! I appreciate the compliment!", | |
| "Thanks! I try my best to be helpful and friendly!", | |
| "Thank you! You seem pretty awesome yourself!" | |
| ], | |
| "weather": [ | |
| "I wish I could check the weather for you! I don't have access to live weather data, but I hope it's nice where you are!", | |
| "Weather can really affect our mood! I hope you're experiencing pleasant conditions!", | |
| "I'd love to help with weather info, but I don't have that capability. Maybe check a weather app?" | |
| ], | |
| "time": [ | |
| f"The current time is {datetime.now().strftime('%H:%M:%S')}. Thanks for asking!", | |
| f"It's {datetime.now().strftime('%I:%M %p')} right now. Time flies when you're chatting!", | |
| f"The timestamp shows {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}." | |
| ], | |
| "default": [ | |
| "That's interesting! Tell me more about that.", | |
| "I see! What else is on your mind?", | |
| "Fascinating! I'd love to hear more thoughts on this topic.", | |
| "Thanks for sharing that! How do you feel about it?", | |
| "That's a great point! What's your experience with that?", | |
| "I appreciate you telling me that. What would you like to explore next?", | |
| "Sounds good! I'm all ears if you want to continue the conversation." | |
| ] | |
| } | |
| # Keywords for response classification | |
| KEYWORDS = { | |
| "greetings": ["hello", "hi", "hey", "good morning", "good afternoon", "good evening"], | |
| "goodbyes": ["bye", "goodbye", "see you", "farewell", "talk later", "gotta go"], | |
| "how_are_you": ["how are you", "how are things", "how's it going", "how do you feel"], | |
| "questions": ["what", "why", "how", "when", "where", "who", "?"], | |
| "compliments": ["great", "awesome", "amazing", "wonderful", "fantastic", "good job", "well done"], | |
| "weather": ["weather", "temperature", "rain", "sunny", "cloudy", "forecast"], | |
| "time": ["time", "clock", "date", "when is it"] | |
| } | |
| def classify_message(message): | |
| """Classify the user's message to determine appropriate response category.""" | |
| message_lower = message.lower() | |
| for category, keywords in KEYWORDS.items(): | |
| if any(keyword in message_lower for keyword in keywords): | |
| return category | |
| return "default" | |
| def get_bot_response(message): | |
| """Generate an appropriate bot response based on the message.""" | |
| category = classify_message(message) | |
| responses = BOT_RESPONSES.get(category, BOT_RESPONSES["default"]) | |
| return random.choice(responses) | |
| def add_message(sender, content): | |
| """Add a message to the chat history.""" | |
| timestamp = datetime.now().strftime("%H:%M:%S") | |
| st.session_state.messages.append({ | |
| "sender": sender, | |
| "content": content, | |
| "timestamp": timestamp | |
| }) | |
| def display_message(msg): | |
| """Display a single message with appropriate styling.""" | |
| if msg["sender"] == "user": | |
| st.markdown(f""" | |
| <div class="user-message"> | |
| <div>{msg['content']}</div> | |
| <div class="message-timestamp">{msg['timestamp']}</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| else: | |
| st.markdown(f""" | |
| <div class="bot-message"> | |
| <div>{msg['content']}</div> | |
| <div class="message-timestamp">{msg['timestamp']}</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| def typing_animation(): | |
| """Show typing animation.""" | |
| with st.empty(): | |
| for i in range(3): | |
| st.markdown(f""" | |
| <div class="typing-indicator"> | |
| Bot is typing{'.' * (i + 1)} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| time.sleep(0.5) | |
| st.empty() | |
| # Sidebar | |
| with st.sidebar: | |
| st.markdown('<div class="sidebar-info">', unsafe_allow_html=True) | |
| st.markdown("### π€ Chatbot Info") | |
| st.markdown("**Built with anycoder**") | |
| st.markdown("---") | |
| st.markdown("**Chat ID:** `{}`".format(st.session_state.chat_id[:8])) | |
| st.markdown("**Messages:** `{}`".format(len(st.session_state.messages))) | |
| st.markdown("**Started:** `{}`".format(datetime.now().strftime("%Y-%m-%d %H:%M"))) | |
| # User settings | |
| st.markdown("### π€ User Settings") | |
| new_name = st.text_input("Your name:", value=st.session_state.user_name) | |
| if new_name != st.session_state.user_name: | |
| st.session_state.user_name = new_name | |
| st.rerun() | |
| st.markdown("### ποΈ Chat Options") | |
| if st.button("ποΈ Clear Chat", use_container_width=True): | |
| st.session_state.messages = [] | |
| st.rerun() | |
| if st.button("πΎ Export Chat", use_container_width=True): | |
| if st.session_state.messages: | |
| chat_export = json.dumps(st.session_state.messages, indent=2) | |
| st.download_button( | |
| label="π₯ Download Chat History", | |
| data=chat_export, | |
| file_name=f"chat_history_{st.session_state.chat_id[:8]}.json", | |
| mime="application/json" | |
| ) | |
| else: | |
| st.info("No messages to export yet!") | |
| st.markdown('</div>', unsafe_allow_html=True) | |
| # Main chat interface | |
| st.markdown(""" | |
| <div class="chat-header"> | |
| <h1>π€ AI Chatbot</h1> | |
| <p>Welcome to your intelligent chat companion! Built with anycoder</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Display chat history | |
| chat_container = st.container() | |
| with chat_container: | |
| if st.session_state.messages: | |
| for msg in st.session_state.messages: | |
| display_message(msg) | |
| else: | |
| st.markdown(""" | |
| <div style="text-align: center; padding: 50px; color: #666;"> | |
| <h3>π Start a conversation!</h3> | |
| <p>Type a message below to begin chatting with the bot.</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Chat input | |
| st.markdown("---") | |
| input_col1, input_col2 = st.columns([4, 1]) | |
| with input_col1: | |
| if "current_input" not in st.session_state: | |
| st.session_state.current_input = "" | |
| user_input = st.text_input( | |
| "π¬ Type your message:", | |
| value=st.session_state.current_input, | |
| key="message_input", | |
| placeholder="Type something to say...", | |
| label_visibility="collapsed" | |
| ) | |
| with input_col2: | |
| send_button = st.button("π Send", use_container_width=True) | |
| # Handle user input | |
| if send_button and user_input.strip(): | |
| # Add user message | |
| add_message("user", user_input.strip()) | |
| st.session_state.current_input = "" | |
| # Show typing animation | |
| typing_animation() | |
| # Generate and add bot response | |
| bot_response = get_bot_response(user_input.strip()) | |
| add_message("bot", bot_response) | |
| # Rerun to update the display | |
| st.rerun() | |
| # Quick action buttons | |
| st.markdown("### π‘ Quick Actions") | |
| quick_col1, quick_col2, quick_col3 = st.columns(3) | |
| with quick_col1: | |
| if st.button("π Say Hello", use_container_width=True): | |
| if not any("user" in msg and "hello" in msg["content"].lower() for msg in st.session_state.messages[-3:]): | |
| add_message("user", "Hello there!") | |
| typing_animation() | |
| add_message("bot", random.choice(BOT_RESPONSES["greetings"])) | |
| st.rerun() | |
| with quick_col2: | |
| if st.button("β Ask Question", use_container_width=True): | |
| add_message("user", "Can you help me with something?") | |
| typing_animation() | |
| add_message("bot", "Of course! I'm here to help. What would you like to know?") | |
| st.rerun() | |
| with quick_col3: | |
| if st.button("π€ Random Topic", use_container_width=True): | |
| topics = [ | |
| "What's your favorite hobby?", | |
| "Tell me something interesting!", | |
| "What do you think about technology?", | |
| "What's the best thing that happened today?", | |
| "Do you have any advice for me?" | |
| ] | |
| random_topic = random.choice(topics) | |
| add_message("user", random_topic) | |
| typing_animation() | |
| add_message("bot", random.choice(BOT_RESPONSES["default"])) | |
| st.rerun() | |
| # Footer | |
| st.markdown("---") | |
| st.markdown(""" | |
| <div style="text-align: center; color: #666; font-size: 0.9em;"> | |
| <p>π€ Powered by <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #667eea;">anycoder</a> | | |
| Built with β€οΈ using Streamlit</p> | |
| <p>π¬ This is a demo chatbot with simulated responses</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| === requirements.txt === | |
| streamlit | |
| pandas | |
| numpy | |
| This chatbot application includes: | |
| ## Features: | |
| - **Modern Chat Interface**: Clean, responsive design with styled message bubbles | |
| - **Real-time Chat**: Instant message exchange with typing animations | |
| - **Chat History**: Persistent session state maintaining conversation | |
| - **Smart Responses**: Keyword-based response classification for contextual replies | |
| - **User Customization**: Custom name setting and chat export functionality | |
| - **Quick Actions**: Pre-defined conversation starters | |
| - **Chat Management**: Clear chat and export options | |
| - **Responsive Design**: Works well on desktop and mobile | |
| ## Bot Capabilities: | |
| - **Greetings & Goodbyes**: Appropriate responses for conversation starts/endings | |
| - **Questions**: Responds to question patterns | |
| - **Compliments**: Graceful handling of positive feedback | |
| - **Time/Weather**: Basic information responses | |
| - **Default Conversations**: Various engaging responses for general chat | |
| ## How to Use: | |
| 1. Type messages in the input field and press Send | |
| 2. Use quick action buttons to start conversations | |
| 3. Customize your name in the sidebar | |
| 4. Export chat history as JSON | |
| 5. Clear chat history when needed | |
| The bot uses intelligent keyword classification to provide contextual responses, making conversations feel natural and engaging! |