akhaliq's picture
akhaliq HF Staff
Upload folder using huggingface_hub
63a4de4 verified
raw
history blame
6.53 kB
import gradio as gr
import random
import time
from datetime import datetime
def format_message(role, content, timestamp):
"""Format a chat message as HTML"""
avatar = "πŸ€–" if role == "assistant" else "πŸ‘€"
bg_color = "#f0f0f0" if role == "assistant" else "#e3f2fd"
align = "flex-start" if role == "assistant" else "flex-end"
html = f"""
<div style="display: flex; justify-content: {align}; margin: 10px 0;">
<div style="max-width: 70%; background: {bg_color}; padding: 12px 16px; border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<div style="display: flex; align-items: center; margin-bottom: 4px;">
<span style="font-size: 20px; margin-right: 8px;">{avatar}</span>
<span style="font-weight: 600; color: #333;">{role.capitalize()}</span>
<span style="margin-left: auto; font-size: 11px; color: #666;">{timestamp}</span>
</div>
<div style="color: #222; line-height: 1.5; white-space: pre-wrap;">{content}</div>
</div>
</div>
"""
return html
def create_chat_html(messages):
"""Create HTML for entire chat history"""
if not messages:
return """
<div style="text-align: center; padding: 40px; color: #999;">
<h3>No messages yet</h3>
<p>Start a conversation by typing a message below!</p>
</div>
"""
chat_html = """
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;">
"""
for msg in messages:
chat_html += format_message(
msg["role"],
msg["content"],
msg["timestamp"]
)
chat_html += "</div>"
return chat_html
def respond(message, history):
"""Generate bot response"""
timestamp = datetime.now().strftime("%H:%M")
# Add user message to history
history.append({
"role": "user",
"content": message,
"timestamp": timestamp
})
# Simulate thinking
time.sleep(0.5)
# Generate bot response
responses = [
"That's an interesting point! Tell me more about that.",
"I understand what you're saying. How does that make you feel?",
"Thanks for sharing! I'm here to help with any questions you have.",
"Great question! Let me think about that for a moment...",
"I appreciate your perspective on this topic.",
"That's a good observation. What else would you like to discuss?",
"Interesting! I'd love to hear more details about that.",
"I see where you're coming from. Let's explore this further.",
]
# Add some context-aware responses
if "hello" in message.lower() or "hi" in message.lower():
bot_response = "Hello! How can I assist you today? 😊"
elif "bye" in message.lower() or "goodbye" in message.lower():
bot_response = "Goodbye! It was nice chatting with you. Have a great day! πŸ‘‹"
elif "help" in message.lower():
bot_response = "I'm here to help! You can ask me anything, and I'll do my best to assist you. What would you like to know?"
elif "?" in message:
bot_response = f"That's a great question! {random.choice(responses)}"
else:
bot_response = random.choice(responses)
# Add bot message to history
history.append({
"role": "assistant",
"content": bot_response,
"timestamp": datetime.now().strftime("%H:%M")
})
return create_chat_html(history), history, ""
def clear_chat():
"""Clear chat history"""
return create_chat_html([]), [], ""
# Custom CSS for better styling
custom_css = """
#chat-container {
height: 500px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
background: white;
}
#chat-container::-webkit-scrollbar {
width: 8px;
}
#chat-container::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
#chat-container::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
#chat-container::-webkit-scrollbar-thumb:hover {
background: #555;
}
.input-row {
margin-top: 16px;
}
footer {
text-align: center;
margin-top: 20px;
padding: 10px;
color: #666;
}
"""
# Create the Gradio interface
with gr.Blocks(css=custom_css, title="HTML Chatbot", fill_height=True) as demo:
gr.Markdown(
"""
# πŸ€– Custom HTML Chatbot
### A beautiful chatbot built with gr.HTML component
<p style='text-align: center;'>
<a href='https://huggingface.co/spaces/akhaliq/anycoder' target='_blank' style='text-decoration: none; color: #4A90E2;'>
Built with anycoder
</a>
</p>
"""
)
# State to store chat history
chat_history = gr.State([])
# Chat display using HTML component
chat_display = gr.HTML(
value=create_chat_html([]),
elem_id="chat-container"
)
# Input row
with gr.Row(elem_classes="input-row"):
with gr.Column(scale=9):
message_input = gr.Textbox(
placeholder="Type your message here...",
show_label=False,
container=False,
autofocus=True
)
with gr.Column(scale=1, min_width=100):
send_btn = gr.Button("Send", variant="primary")
with gr.Row():
clear_btn = gr.Button("Clear Chat", variant="secondary", size="sm")
# Event handlers
send_btn.click(
fn=respond,
inputs=[message_input, chat_history],
outputs=[chat_display, chat_history, message_input],
api_name="send_message"
)
message_input.submit(
fn=respond,
inputs=[message_input, chat_history],
outputs=[chat_display, chat_history, message_input],
api_name=False
)
clear_btn.click(
fn=clear_chat,
inputs=[],
outputs=[chat_display, chat_history, message_input],
api_name="clear_chat"
)
gr.Markdown(
"""
---
### Features:
- 🎨 Custom HTML rendering for beautiful message display
- ⏰ Timestamps for each message
- πŸ‘€ User and bot avatars
- 🎯 Context-aware responses
- 🧹 Clear chat functionality
- πŸ“± Responsive design
"""
)
if __name__ == "__main__":
demo.launch()