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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import random
|
| 3 |
+
import time
|
| 4 |
+
from typing import List, Tuple
|
| 5 |
+
|
| 6 |
+
# Mock AI responses for demonstration
|
| 7 |
+
def get_ai_response(user_message: str, chat_history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
|
| 8 |
+
"""
|
| 9 |
+
Simulates an AI chatbot response.
|
| 10 |
+
In a real application, you would connect this to an actual AI model.
|
| 11 |
+
"""
|
| 12 |
+
# Simple pattern matching for demonstration
|
| 13 |
+
user_message_lower = user_message.lower()
|
| 14 |
+
|
| 15 |
+
if "hello" in user_message_lower or "hi" in user_message_lower:
|
| 16 |
+
responses = [
|
| 17 |
+
"Hello there! How can I assist you today?",
|
| 18 |
+
"Hi! Nice to meet you!",
|
| 19 |
+
"Greetings! What can I help you with today?"
|
| 20 |
+
]
|
| 21 |
+
elif "how are you" in user_message_lower:
|
| 22 |
+
responses = [
|
| 23 |
+
"I'm doing great! Just here ready to chat with you.",
|
| 24 |
+
"I'm functioning perfectly! How about you?",
|
| 25 |
+
"All systems operational! What's on your mind?"
|
| 26 |
+
]
|
| 27 |
+
elif "weather" in user_message_lower:
|
| 28 |
+
responses = [
|
| 29 |
+
"I don't have real-time weather data, but I hope it's pleasant wherever you are!",
|
| 30 |
+
"I'm an AI, so I don't experience weather, but I can discuss it with you!"
|
| 31 |
+
]
|
| 32 |
+
elif "help" in user_message_lower:
|
| 33 |
+
responses = [
|
| 34 |
+
"I'm here to help! You can ask me about various topics, or we can just have a friendly conversation!"
|
| 35 |
+
]
|
| 36 |
+
elif "bye" in user_message_lower or "goodbye" in user_message_lower:
|
| 37 |
+
responses = [
|
| 38 |
+
"Goodbye! It was nice chatting with you!",
|
| 39 |
+
"Farewell! Hope to talk with you again soon!",
|
| 40 |
+
"See you later! Don't hesitate to come back if you have more questions!"
|
| 41 |
+
]
|
| 42 |
+
else:
|
| 43 |
+
responses = [
|
| 44 |
+
"That's interesting! Tell me more about that.",
|
| 45 |
+
"I appreciate you sharing that with me.",
|
| 46 |
+
"That's fascinating! I'd love to hear more."
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
# Add some randomness and thinking simulation
|
| 50 |
+
thinking_time = random.uniform(0.5, 2.0)
|
| 51 |
+
time.sleep(thinking_time)
|
| 52 |
+
|
| 53 |
+
return random.choice(responses), chat_history + [(user_message, random.choice(responses))]
|
| 54 |
+
|
| 55 |
+
def stream_ai_response(user_message: str, chat_history: List[Tuple[str, str]]):
|
| 56 |
+
"""
|
| 57 |
+
Streams AI responses character by character for a more natural feel.
|
| 58 |
+
"""
|
| 59 |
+
full_response, chat_history = get_ai_response(user_message, chat_history)
|
| 60 |
+
for i in range(len(full_response)):
|
| 61 |
+
partial_response = full_response[:i+1]
|
| 62 |
+
yield partial_response, chat_history + [(user_message, partial_response)]
|
| 63 |
+
|
| 64 |
+
def handle_user_input(user_message: str, chat_history: List[Tuple[str, str]]):
|
| 65 |
+
"""Process user input and update chat history."""
|
| 66 |
+
if not user_message.strip():
|
| 67 |
+
return "", chat_history
|
| 68 |
+
|
| 69 |
+
# Get AI response
|
| 70 |
+
ai_response, chat_history = get_ai_response(user_message, chat_history)
|
| 71 |
+
|
| 72 |
+
return "", chat_history
|
| 73 |
+
|
| 74 |
+
def clear_chat():
|
| 75 |
+
"""Clear the chat history."""
|
| 76 |
+
return [], []
|
| 77 |
+
|
| 78 |
+
def like_message():
|
| 79 |
+
"""Handle message liking."""
|
| 80 |
+
gr.Info("Thanks for the feedback!")
|
| 81 |
+
|
| 82 |
+
def retry_message():
|
| 83 |
+
"""Handle message retry."""
|
| 84 |
+
gr.Warning("Retrying the last response...")
|
| 85 |
+
|
| 86 |
+
# Create custom theme for the chatbot
|
| 87 |
+
custom_theme = gr.themes.Soft(
|
| 88 |
+
primary_hue="indigo",
|
| 89 |
+
secondary_hue="blue",
|
| 90 |
+
neutral_hue="slate",
|
| 91 |
+
font=gr.themes.GoogleFont("Inter"),
|
| 92 |
+
text_size="lg",
|
| 93 |
+
spacing_size="lg",
|
| 94 |
+
radius_size="md"
|
| 95 |
+
).set(
|
| 96 |
+
button_primary_background_fill="*primary_600",
|
| 97 |
+
button_primary_background_fill_hover="*primary_700",
|
| 98 |
+
block_title_text_weight="600",
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
with gr.Blocks() as demo:
|
| 102 |
+
# Header with title and anycoder link
|
| 103 |
+
with gr.Row():
|
| 104 |
+
gr.Markdown("# π€ AI Chatbot")
|
| 105 |
+
gr.HTML(
|
| 106 |
+
'<div style="text-align: right; font-size: 0.8em;">'
|
| 107 |
+
'<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #6B7280; text-decoration: none;">'
|
| 108 |
+
'Built with anycoder'
|
| 109 |
+
'</a>'
|
| 110 |
+
'</div>'
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Description
|
| 114 |
+
gr.Markdown(
|
| 115 |
+
"Welcome to your AI assistant! I'm here to help with questions, "
|
| 116 |
+
"have conversations, or just chat about whatever's on your mind."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# Chat interface
|
| 120 |
+
with gr.Row():
|
| 121 |
+
with gr.Column(scale=3):
|
| 122 |
+
chatbot = gr.Chatbot(
|
| 123 |
+
label="Chat",
|
| 124 |
+
height=500,
|
| 125 |
+
show_copy_button=True,
|
| 126 |
+
show_share_button=True,
|
| 127 |
+
placeholder="Type your message here...",
|
| 128 |
+
show_clear_button=True,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
with gr.Column(scale=2):
|
| 132 |
+
# Input controls
|
| 133 |
+
with gr.Group():
|
| 134 |
+
user_input = gr.Textbox(
|
| 135 |
+
label="Your Message",
|
| 136 |
+
placeholder="Type your message here and press Enter...",
|
| 137 |
+
lines=2,
|
| 138 |
+
max_lines=5,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
with gr.Row():
|
| 142 |
+
send_btn = gr.Button("Send", variant="primary")
|
| 143 |
+
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
| 144 |
+
|
| 145 |
+
# Additional controls
|
| 146 |
+
with gr.Accordion("Advanced Options", open=False):
|
| 147 |
+
with gr.Row():
|
| 148 |
+
like_btn = gr.Button("π Like", size="sm")
|
| 149 |
+
retry_btn = gr.Button("π Retry", size="sm")
|
| 150 |
+
|
| 151 |
+
# Status indicators
|
| 152 |
+
with gr.Row():
|
| 153 |
+
gr.Markdown("**Status:** Ready")
|
| 154 |
+
|
| 155 |
+
# Event handling
|
| 156 |
+
send_btn.click(
|
| 157 |
+
fn=handle_user_input,
|
| 158 |
+
inputs=[user_input, chatbot],
|
| 159 |
+
outputs=[user_input, chatbot],
|
| 160 |
+
api_visibility="public"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
user_input.submit(
|
| 164 |
+
fn=handle_user_input,
|
| 165 |
+
inputs=[user_input, chatbot],
|
| 166 |
+
outputs=[user_input, chatbot],
|
| 167 |
+
api_visibility="public"
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
clear_btn.click(
|
| 171 |
+
fn=clear_chat,
|
| 172 |
+
inputs=None,
|
| 173 |
+
outputs=[chatbot, user_input],
|
| 174 |
+
api_visibility="public"
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
like_btn.click(
|
| 178 |
+
fn=like_message,
|
| 179 |
+
inputs=None,
|
| 180 |
+
outputs=None,
|
| 181 |
+
api_visibility="private"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
retry_btn.click(
|
| 185 |
+
fn=retry_message,
|
| 186 |
+
inputs=None,
|
| 187 |
+
outputs=None,
|
| 188 |
+
api_visibility="private"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# Streaming example
|
| 192 |
+
with gr.Group(visible=False) as streaming_section:
|
| 193 |
+
gr.Markdown("### Streaming Response Demo")
|
| 194 |
+
streaming_input = gr.Textbox(label="Streaming test message")
|
| 195 |
+
streaming_output = gr.Textbox(label="Streaming response", interactive=False)
|
| 196 |
+
|
| 197 |
+
# Examples
|
| 198 |
+
gr.Examples(
|
| 199 |
+
examples=[
|
| 200 |
+
"Hello, how are you today?",
|
| 201 |
+
"What's the weather like?",
|
| 202 |
+
"Can you help me with something?",
|
| 203 |
+
"Tell me a fun fact!",
|
| 204 |
+
"What can you do as an AI assistant?"
|
| 205 |
+
],
|
| 206 |
+
inputs=user_input
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Launch the application with modern Gradio 6 syntax
|
| 210 |
+
demo.launch(
|
| 211 |
+
theme=custom_theme,
|
| 212 |
+
footer_links=[
|
| 213 |
+
{"label": "API Documentation", "url": "/docs"},
|
| 214 |
+
{"label": "About", "url": "/about"}
|
| 215 |
+
],
|
| 216 |
+
share=False, # Set to True for public sharing
|
| 217 |
+
show_error=True,
|
| 218 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=6.0
|
| 2 |
+
requests
|
| 3 |
+
Pillow
|
utils.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utility functions for the AI Chatbot application.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
def format_chat_message(role: str, content: str) -> dict:
|
| 6 |
+
"""Format a chat message for the chatbot component."""
|
| 7 |
+
return {"role": role, "content": content}
|
| 8 |
+
|
| 9 |
+
def validate_message(message: str) -> bool:
|
| 10 |
+
"""Validate that a message is safe and appropriate."""
|
| 11 |
+
# Simple validation - in production you'd want more robust checks
|
| 12 |
+
forbidden_words = ["hate", "violence", "harm"] # Basic content filtering
|
| 13 |
+
return not any(word in message.lower() for word in forbidden_words)
|
| 14 |
+
|
| 15 |
+
def get_timestamp() -> str:
|
| 16 |
+
"""Get current timestamp for logging."""
|
| 17 |
+
from datetime import datetime
|
| 18 |
+
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
This AI chatbot application features:
|
| 22 |
+
|
| 23 |
+
## π¨ Modern Design
|
| 24 |
+
- **Custom Soft theme** with indigo primary colors
|
| 25 |
+
- **Google Inter font** for clean typography
|
| 26 |
+
- **Responsive layout** that works on different screen sizes
|
| 27 |
+
- **Professional UI** with proper spacing and sizing
|
| 28 |
+
|
| 29 |
+
## π€ Core Features
|
| 30 |
+
- **Interactive chat interface** with message history
|
| 31 |
+
- **Streaming responses** for natural conversation flow
|
| 32 |
+
- **Message actions**: Like and Retry functionality
|
| 33 |
+
- **Chat examples** for users to try
|
| 34 |
+
- **Clear chat functionality**
|
| 35 |
+
|
| 36 |
+
## π Gradio 6 Best Practices
|
| 37 |
+
- β
**Theme in demo.launch()** - Correct Gradio 6 syntax
|
| 38 |
+
- β
**Proper event handling** with api_visibility parameter
|
| 39 |
+
- β
**Responsive components** with appropriate sizing
|
| 40 |
+
- β
**Error handling** and user feedback
|
| 41 |
+
- β
**Clean code structure** with proper documentation
|
| 42 |
+
|
| 43 |
+
## π± User Experience
|
| 44 |
+
- **Intuitive input** with placeholder text
|
| 45 |
+
- **Visual feedback** through info/warning messages
|
| 46 |
+
- **Copy and share** buttons for chat messages
|
| 47 |
+
- **Accessibility** with proper labels and descriptions
|
| 48 |
+
|
| 49 |
+
The chatbot uses simulated AI responses with pattern matching, but you can easily replace this with actual AI model integrations (OpenAI, Hugging Face, etc.).
|