File size: 7,104 Bytes
76c14bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
218
import gradio as gr
import random
import time
from typing import List, Tuple

# Mock AI responses for demonstration
def get_ai_response(user_message: str, chat_history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
    """
    Simulates an AI chatbot response.
    In a real application, you would connect this to an actual AI model.
    """
    # Simple pattern matching for demonstration
    user_message_lower = user_message.lower()
    
    if "hello" in user_message_lower or "hi" in user_message_lower:
        responses = [
            "Hello there! How can I assist you today?",
            "Hi! Nice to meet you!",
            "Greetings! What can I help you with today?"
        ]
    elif "how are you" in user_message_lower:
        responses = [
            "I'm doing great! Just here ready to chat with you.",
            "I'm functioning perfectly! How about you?",
            "All systems operational! What's on your mind?"
        ]
    elif "weather" in user_message_lower:
        responses = [
            "I don't have real-time weather data, but I hope it's pleasant wherever you are!",
            "I'm an AI, so I don't experience weather, but I can discuss it with you!"
        ]
    elif "help" in user_message_lower:
        responses = [
            "I'm here to help! You can ask me about various topics, or we can just have a friendly conversation!"
        ]
    elif "bye" in user_message_lower or "goodbye" in user_message_lower:
        responses = [
            "Goodbye! It was nice chatting with you!",
            "Farewell! Hope to talk with you again soon!",
            "See you later! Don't hesitate to come back if you have more questions!"
        ]
    else:
        responses = [
            "That's interesting! Tell me more about that.",
            "I appreciate you sharing that with me.",
            "That's fascinating! I'd love to hear more."
        ]
    
    # Add some randomness and thinking simulation
    thinking_time = random.uniform(0.5, 2.0)
    time.sleep(thinking_time)
    
    return random.choice(responses), chat_history + [(user_message, random.choice(responses))]

def stream_ai_response(user_message: str, chat_history: List[Tuple[str, str]]):
    """
    Streams AI responses character by character for a more natural feel.
    """
    full_response, chat_history = get_ai_response(user_message, chat_history)
    for i in range(len(full_response)):
        partial_response = full_response[:i+1]
        yield partial_response, chat_history + [(user_message, partial_response)]

def handle_user_input(user_message: str, chat_history: List[Tuple[str, str]]):
    """Process user input and update chat history."""
    if not user_message.strip():
        return "", chat_history
    
    # Get AI response
    ai_response, chat_history = get_ai_response(user_message, chat_history)
    
    return "", chat_history

def clear_chat():
    """Clear the chat history."""
    return [], []

def like_message():
    """Handle message liking."""
    gr.Info("Thanks for the feedback!")

def retry_message():
    """Handle message retry."""
    gr.Warning("Retrying the last response...")

# Create custom theme for the chatbot
custom_theme = gr.themes.Soft(
    primary_hue="indigo",
    secondary_hue="blue",
    neutral_hue="slate",
    font=gr.themes.GoogleFont("Inter"),
    text_size="lg",
    spacing_size="lg",
    radius_size="md"
).set(
    button_primary_background_fill="*primary_600",
    button_primary_background_fill_hover="*primary_700",
    block_title_text_weight="600",
)

with gr.Blocks() as demo:
    # Header with title and anycoder link
    with gr.Row():
        gr.Markdown("# πŸ€– AI Chatbot")
        gr.HTML(
            '<div style="text-align: right; font-size: 0.8em;">'
            '<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #6B7280; text-decoration: none;">'
            'Built with anycoder'
            '</a>'
            '</div>'
        )
    
    # Description
    gr.Markdown(
        "Welcome to your AI assistant! I'm here to help with questions, "
        "have conversations, or just chat about whatever's on your mind."
    )
    
    # Chat interface
    with gr.Row():
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(
                label="Chat",
                height=500,
                show_copy_button=True,
                show_share_button=True,
                placeholder="Type your message here...",
            show_clear_button=True,
            )
    
    with gr.Column(scale=2):
        # Input controls
        with gr.Group():
            user_input = gr.Textbox(
                label="Your Message",
                placeholder="Type your message here and press Enter...",
                lines=2,
                max_lines=5,
                )
            
            with gr.Row():
                send_btn = gr.Button("Send", variant="primary")
                clear_btn = gr.Button("Clear Chat", variant="secondary")
        
        # Additional controls
        with gr.Accordion("Advanced Options", open=False):
            with gr.Row():
                like_btn = gr.Button("πŸ‘ Like", size="sm")
                retry_btn = gr.Button("πŸ”„ Retry", size="sm")
        
        # Status indicators
        with gr.Row():
            gr.Markdown("**Status:** Ready")
    
    # Event handling
    send_btn.click(
        fn=handle_user_input,
        inputs=[user_input, chatbot],
        outputs=[user_input, chatbot],
        api_visibility="public"
        )
        
        user_input.submit(
            fn=handle_user_input,
            inputs=[user_input, chatbot],
        outputs=[user_input, chatbot],
        api_visibility="public"
        )
    
    clear_btn.click(
        fn=clear_chat,
        inputs=None,
        outputs=[chatbot, user_input],
        api_visibility="public"
        )
    
    like_btn.click(
        fn=like_message,
        inputs=None,
        outputs=None,
        api_visibility="private"
        )
    
    retry_btn.click(
        fn=retry_message,
        inputs=None,
        outputs=None,
        api_visibility="private"
        )
    
    # Streaming example
    with gr.Group(visible=False) as streaming_section:
        gr.Markdown("### Streaming Response Demo")
        streaming_input = gr.Textbox(label="Streaming test message")
        streaming_output = gr.Textbox(label="Streaming response", interactive=False)
    
    # Examples
    gr.Examples(
        examples=[
            "Hello, how are you today?",
            "What's the weather like?",
            "Can you help me with something?",
            "Tell me a fun fact!",
            "What can you do as an AI assistant?"
        ],
        inputs=user_input
        )

# Launch the application with modern Gradio 6 syntax
demo.launch(
    theme=custom_theme,
    footer_links=[
        {"label": "API Documentation", "url": "/docs"},
        {"label": "About", "url": "/about"}
    ],
    share=False,  # Set to True for public sharing
    show_error=True,
    )