akhaliq HF Staff commited on
Commit
7682356
Β·
verified Β·
1 Parent(s): 942bed9

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +265 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import time
4
+ from typing import List, Dict, Any
5
+
6
+ # Sample responses for the chatbot
7
+ RESPONSES = [
8
+ "That's an interesting question! Let me think about it...",
9
+ "I understand what you're saying. Here's my perspective...",
10
+ "Great point! Have you considered this as well?",
11
+ "I'm here to help! What would you like to know more about?",
12
+ "That reminds me of something important I'd like to share...",
13
+ "Thanks for sharing that with me. Let me provide some insights...",
14
+ "I appreciate your question. Here's what I think...",
15
+ "Absolutely! Let me elaborate on that topic...",
16
+ ]
17
+
18
+ def generate_response(message: str, history: List[Dict[str, str]]) -> str:
19
+ """Generate a response based on the user message and chat history."""
20
+ # Simple logic - in a real app, this would call an AI model
21
+ time.sleep(0.5) # Simulate thinking time
22
+
23
+ # Check for specific keywords to provide more relevant responses
24
+ message_lower = message.lower()
25
+ if "hello" in message_lower or "hi" in message_lower:
26
+ return "Hello! It's great to chat with you today. How can I assist you?"
27
+ elif "how are you" in message_lower:
28
+ return "I'm doing wonderfully, thank you for asking! I'm here and ready to help you with anything you need."
29
+ elif "bye" in message_lower or "goodbye" in message_lower:
30
+ return "Goodbye! It was a pleasure chatting with you. Feel free to come back anytime!"
31
+ elif "help" in message_lower:
32
+ return "I'm here to help! You can ask me questions, share your thoughts, or just have a friendly conversation. What's on your mind?"
33
+ elif "thank" in message_lower:
34
+ return "You're very welcome! I'm always happy to assist. Is there anything else I can help you with?"
35
+ else:
36
+ # Return a random response
37
+ return random.choice(RESPONSES)
38
+
39
+ def user_input(user_message: str, history: List[Dict[str, str]]) -> tuple[str, List[Dict[str, str]]]:
40
+ """Process user input and add it to the chat history."""
41
+ if not user_message.strip():
42
+ return "", history
43
+
44
+ # Add user message to history
45
+ history.append({"role": "user", "content": user_message})
46
+ return "", history
47
+
48
+ def bot_response(history: List[Dict[str, str]]) -> List[Dict[str, str]]:
49
+ """Generate and add bot response to the chat history."""
50
+ if not history:
51
+ return history
52
+
53
+ last_message = history[-1]["content"]
54
+ bot_message = generate_response(last_message, history)
55
+
56
+ # Add bot message to history
57
+ history.append({"role": "assistant", "content": bot_message})
58
+ return history
59
+
60
+ def stream_response(message: str, history: List[Dict[str, str]]):
61
+ """Stream the bot response character by character."""
62
+ if not history:
63
+ return
64
+
65
+ last_message = history[-1]["content"]
66
+ full_response = generate_response(last_message, history)
67
+
68
+ # Add empty bot message to history
69
+ history.append({"role": "assistant", "content": ""})
70
+
71
+ # Stream the response
72
+ for i in range(len(full_response)):
73
+ history[-1]["content"] = full_response[:i+1]
74
+ yield history
75
+ time.sleep(0.02) # Small delay for streaming effect
76
+
77
+ # Example conversations
78
+ EXAMPLE_CONVERSATIONS = [
79
+ ["Hello! How are you today?"],
80
+ ["Can you help me with something?"],
81
+ ["What's the weather like?"],
82
+ ["Tell me an interesting fact"],
83
+ ["Thank you for your help!"]
84
+ ]
85
+
86
+ # Custom CSS for better styling
87
+ CUSTOM_CSS = """
88
+ .chat-container {
89
+ height: 500px;
90
+ overflow-y: auto;
91
+ }
92
+ .message {
93
+ padding: 10px;
94
+ margin: 5px;
95
+ border-radius: 10px;
96
+ max-width: 80%;
97
+ }
98
+ .user-message {
99
+ background-color: #e3f2fd;
100
+ margin-left: auto;
101
+ text-align: right;
102
+ }
103
+ .bot-message {
104
+ background-color: #f3e5f5;
105
+ }
106
+ """
107
+
108
+ with gr.Blocks(
109
+ title="AI Chatbot Assistant",
110
+ theme=gr.themes.Soft(),
111
+ css=CUSTOM_CSS
112
+ ) as demo:
113
+ # Header with branding
114
+ gr.HTML("""
115
+ <div style="text-align: center; margin-bottom: 20px;">
116
+ <h1>πŸ€– AI Chatbot Assistant</h1>
117
+ <p>Your friendly AI companion for engaging conversations</p>
118
+ <p style="font-size: 0.9em; color: #666;">
119
+ Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">anycoder</a>
120
+ </p>
121
+ </div>
122
+ """)
123
+
124
+ # Chat interface
125
+ with gr.Row():
126
+ with gr.Column(scale=4):
127
+ chatbot = gr.Chatbot(
128
+ label="Conversation",
129
+ height=500,
130
+ show_copy_button=True,
131
+ placeholder="Start a conversation by typing a message below...",
132
+ avatar_images=(
133
+ None, # User avatar (default)
134
+ "https://picsum.photos/seed/ai-avatar/100/100.jpg" # Bot avatar
135
+ ),
136
+ type="messages"
137
+ )
138
+
139
+ with gr.Row():
140
+ msg = gr.Textbox(
141
+ label="Your Message",
142
+ placeholder="Type your message here and press Enter...",
143
+ lines=1,
144
+ max_lines=5,
145
+ container=False,
146
+ scale=4
147
+ )
148
+ submit_btn = gr.Button(
149
+ "Send",
150
+ variant="primary",
151
+ scale=1,
152
+ size="sm"
153
+ )
154
+
155
+ with gr.Row():
156
+ clear_btn = gr.Button(
157
+ "Clear Conversation",
158
+ variant="secondary",
159
+ scale=1,
160
+ size="sm"
161
+ )
162
+ example_btn = gr.Button(
163
+ "Random Example",
164
+ variant="secondary",
165
+ scale=1,
166
+ size="sm"
167
+ )
168
+
169
+ with gr.Column(scale=1):
170
+ gr.Markdown("### πŸ’‘ Tips")
171
+ gr.Markdown("""
172
+ - Type your message and press Enter or click Send
173
+ - Use the Clear button to start fresh
174
+ - Try the Random Example button for conversation starters
175
+ - Click on messages to copy them
176
+ """)
177
+
178
+ gr.Markdown("### πŸ“Š Stats")
179
+ message_count = gr.Number(
180
+ label="Messages",
181
+ value=0,
182
+ interactive=False
183
+ )
184
+
185
+ gr.Markdown("### 🎯 Quick Actions")
186
+ gr.Examples(
187
+ examples=EXAMPLE_CONVERSATIONS,
188
+ inputs=msg,
189
+ label="Example Messages",
190
+ examples_per_page=5
191
+ )
192
+
193
+ # Event handlers
194
+ def update_message_count(history: List[Dict[str, str]]) -> int:
195
+ """Update the message count display."""
196
+ return len(history) if history else 0
197
+
198
+ # Handle user input and generate streaming response
199
+ msg.submit(
200
+ user_input,
201
+ [msg, chatbot],
202
+ [msg, chatbot],
203
+ queue=False
204
+ ).then(
205
+ stream_response,
206
+ [msg, chatbot],
207
+ chatbot
208
+ ).then(
209
+ update_message_count,
210
+ chatbot,
211
+ message_count
212
+ )
213
+
214
+ submit_btn.click(
215
+ user_input,
216
+ [msg, chatbot],
217
+ [msg, chatbot],
218
+ queue=False
219
+ ).then(
220
+ stream_response,
221
+ [msg, chatbot],
222
+ chatbot
223
+ ).then(
224
+ update_message_count,
225
+ chatbot,
226
+ message_count
227
+ )
228
+
229
+ # Clear conversation
230
+ def clear_conversation():
231
+ """Clear the chat history and reset message count."""
232
+ return [], 0
233
+
234
+ clear_btn.click(
235
+ clear_conversation,
236
+ outputs=[chatbot, message_count]
237
+ )
238
+
239
+ # Random example
240
+ def get_random_example():
241
+ """Get a random example message."""
242
+ return random.choice(EXAMPLE_CONVERSATIONS)[0]
243
+
244
+ example_btn.click(
245
+ get_random_example,
246
+ outputs=msg
247
+ )
248
+
249
+ # Welcome message on load
250
+ demo.load(
251
+ lambda: [{"role": "assistant", "content": "Hello! I'm your AI chatbot assistant. How can I help you today? 😊"}],
252
+ outputs=chatbot
253
+ ).then(
254
+ update_message_count,
255
+ chatbot,
256
+ message_count
257
+ )
258
+
259
+ if __name__ == "__main__":
260
+ demo.launch(
261
+ share=False,
262
+ show_error=True,
263
+ quiet=False,
264
+ show_tips=True
265
+ )
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ Pillow
4
+ numpy
5
+ pandas
6
+ matplotlib
7
+ plotly
8
+ fastapi
9
+ uvicorn
10
+ pydantic