Spaces:
Runtime error
Runtime error
File size: 6,533 Bytes
63a4de4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
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() |