Sathishsri commited on
Commit
0399570
·
verified ·
1 Parent(s): 0f3eccd

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +445 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import time
3
+ import random
4
+ from typing import List, Dict, Any
5
+
6
+ # Simulated responses to mimic a chat assistant
7
+ def get_bot_response(message: str, history: List[Dict[str, str]]) -> str:
8
+ """
9
+ Simulate a chat response. In production, this would connect to an LLM API.
10
+ """
11
+ # Simulate thinking time
12
+ time.sleep(0.5)
13
+
14
+ # Generate contextual responses
15
+ message_lower = message.lower()
16
+
17
+ responses = {
18
+ "hello": [
19
+ "Hello! How can I help you today?",
20
+ "Hi there! What would you like to chat about?",
21
+ "Hey! I'm here to help. What's on your mind?"
22
+ ],
23
+ "hi": [
24
+ "Hello! How can I assist you?",
25
+ "Hi there! What can I do for you?"
26
+ ],
27
+ "how are you": [
28
+ "I'm doing great, thank you for asking! How are you doing?",
29
+ "I'm functioning perfectly and ready to help! What about you?"
30
+ ],
31
+ "help": [
32
+ "I can help you with a variety of tasks! Try asking me about:\n"
33
+ "• Writing and editing text\n"
34
+ "• Answering questions\n"
35
+ "• Code assistance\n"
36
+ "• Brainstorming ideas\n"
37
+ "• And much more!",
38
+ "Sure, I'm here to help! What do you need assistance with?"
39
+ ],
40
+ "thanks": [
41
+ "You're welcome! Is there anything else I can help with?",
42
+ "Happy to help! Let me know if you need anything else."
43
+ ],
44
+ "bye": [
45
+ "Goodbye! Feel free to come back anytime!",
46
+ "See you later! Don't hesitate to return if you need help."
47
+ ]
48
+ }
49
+
50
+ # Check for keyword matches
51
+ for keyword, response_list in responses.items():
52
+ if keyword in message_lower:
53
+ return random.choice(response_list)
54
+
55
+ # Default responses for other inputs
56
+ default_responses = [
57
+ f"That's interesting! Tell me more about that.",
58
+ "I appreciate you sharing that. What else would you like to discuss?",
59
+ "Thanks for bringing that up. Is there anything specific you'd like help with?",
60
+ "Got it! I'd love to hear more. What else is on your mind?",
61
+ "That's a great point! Do you have any questions about it?",
62
+ "I see what you mean. Would you like to explore this further?",
63
+ ]
64
+
65
+ return random.choice(default_responses)
66
+
67
+
68
+ def chat_response(message: str, history: List[List[str]]) -> List[List[str]]:
69
+ """
70
+ Format the chat history and return the bot response.
71
+ Gradio 6 format for Chatbot: List of [user_message, bot_message] pairs.
72
+ """
73
+ # Add user message to history
74
+ history.append([message, ""])
75
+
76
+ # Get bot response
77
+ bot_response = get_bot_response(message, history)
78
+
79
+ # Update the last entry with bot response
80
+ history[-1][1] = bot_response
81
+
82
+ return history
83
+
84
+
85
+ def streaming_response(message: str, history: List[List[str]]) -> List[List[str]]:
86
+ """
87
+ Generate a streaming response for a more ChatGPT-like experience.
88
+ """
89
+ history.append([message, ""])
90
+
91
+ # Get base response
92
+ base_response = get_bot_response(message, history)
93
+
94
+ # Simulate streaming by yielding chunks
95
+ response_so_far = ""
96
+ words = base_response.split()
97
+
98
+ for i, word in enumerate(words):
99
+ response_so_far += word + " "
100
+ history[-1][1] = response_so_far
101
+ yield history
102
+ time.sleep(0.1) # Simulate token streaming
103
+
104
+ # Ensure final response is complete
105
+ history[-1][1] = base_response
106
+ yield history
107
+
108
+
109
+ def clear_chat() -> List[List[str]]:
110
+ """Clear the chat history."""
111
+ return []
112
+
113
+
114
+ def retry_response(message: str, history: List[List[str]]) -> List[List[str]]:
115
+ """
116
+ Retry generating a response for the last user message.
117
+ """
118
+ if not history:
119
+ return history
120
+
121
+ # Remove the last entry and regenerate
122
+ last_user_message = history[-1][0]
123
+ history = history[:-1]
124
+
125
+ # Add new response
126
+ history.append([last_user_message, ""])
127
+ bot_response = get_bot_response(last_user_message, history)
128
+ history[-1][1] = bot_response
129
+
130
+ return history
131
+
132
+
133
+ # Custom CSS for a ChatGPT-like appearance
134
+ custom_css = """
135
+ .gradio-container {
136
+ max-width: 1200px !important;
137
+ margin: 0 auto !important;
138
+ }
139
+
140
+ .chat-message.user {
141
+ background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%) !important;
142
+ color: white !important;
143
+ border-radius: 18px 18px 4px 18px !important;
144
+ }
145
+
146
+ .chat-message.assistant {
147
+ background: linear-gradient(135deg, #f7f7f8 0%, #ececf1 100%) !important;
148
+ border-radius: 18px 18px 18px 4px !important;
149
+ }
150
+
151
+ .chat-message.system {
152
+ background: transparent !important;
153
+ color: #666 !important;
154
+ font-style: italic !important;
155
+ text-align: center !important;
156
+ }
157
+
158
+ #chatbot {
159
+ border-radius: 12px !important;
160
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08) !important;
161
+ }
162
+
163
+ .main-header {
164
+ text-align: center;
165
+ padding: 20px;
166
+ background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%);
167
+ border-radius: 12px;
168
+ margin-bottom: 20px;
169
+ }
170
+
171
+ .main-header h1 {
172
+ color: white !important;
173
+ margin: 0 !important;
174
+ font-size: 2rem !important;
175
+ }
176
+
177
+ .main-header p {
178
+ color: rgba(255, 255, 255, 0.9) !important;
179
+ margin: 8px 0 0 0 !important;
180
+ }
181
+
182
+ /* Custom scrollbar */
183
+ #chatbot::-webkit-scrollbar {
184
+ width: 8px;
185
+ }
186
+
187
+ #chatbot::-webkit-scrollbar-track {
188
+ background: #f1f1f1;
189
+ border-radius: 4px;
190
+ }
191
+
192
+ #chatbot::-webkit-scrollbar-thumb {
193
+ background: #c1c1c1;
194
+ border-radius: 4px;
195
+ }
196
+
197
+ #chatbot::-webkit-scrollbar-thumb:hover {
198
+ background: #a8a8a8;
199
+ }
200
+
201
+ /* Input area styling */
202
+ .message-input {
203
+ border-radius: 24px !important;
204
+ padding: 12px 20px !important;
205
+ }
206
+
207
+ /* Button styling */
208
+ .action-btn {
209
+ border-radius: 8px !important;
210
+ transition: all 0.2s ease !important;
211
+ }
212
+
213
+ .action-btn:hover {
214
+ transform: translateY(-2px) !important;
215
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
216
+ }
217
+ """
218
+
219
+
220
+ def create_chat_app():
221
+ """Create the main chat application."""
222
+
223
+ with gr.Blocks(
224
+ fill_height=True,
225
+ fill_width=True,
226
+ ) as demo:
227
+
228
+ # Header with branding
229
+ gr.HTML("""
230
+ <div class="main-header">
231
+ <h1>🤖 ChatGPT Clone</h1>
232
+ <p>Your AI assistant - Powered by Gradio 6</p>
233
+ </div>
234
+ """)
235
+
236
+ # Add "Built with anycoder" link
237
+ gr.HTML("""
238
+ <div style="text-align: center; margin-bottom: 10px; padding: 8px;">
239
+ <a href="https://huggingface.co/spaces/akhaliq/anycoder"
240
+ target="_blank"
241
+ style="color: #666; text-decoration: none; font-size: 12px; opacity: 0.7;">
242
+ Built with anycoder
243
+ </a>
244
+ </div>
245
+ """)
246
+
247
+ # Chatbot component
248
+ chatbot = gr.Chatbot(
249
+ value=[],
250
+ label="Chat History",
251
+ height=500,
252
+ avatar_images=(
253
+ "https://huggingface.co/datasets/huggingface/avatars/resolve/main/user.png", # User avatar
254
+ "https://huggingface.co/datasets/huggingface/avatars/resolve/main/gradio.png" # Bot avatar
255
+ ),
256
+ latex_delimiters=[
257
+ {"left": "$$", "right": "$$", "display": True},
258
+ {"left": "$", "right": "$", "display": False},
259
+ {"left": "\\(", "right": "\\)", "display": False},
260
+ {"left": "\\[", "right": "\\]", "display": True}
261
+ ],
262
+ elem_id="chatbot",
263
+ resizable=True,
264
+ max_height=600,
265
+ bubble_full_width=False,
266
+ layout="bubble",
267
+ placeholder="Start typing to chat with the AI assistant...",
268
+ examples=[
269
+ ["Hello! How are you?"],
270
+ ["Can you help me write a poem?"],
271
+ ["What is machine learning?"],
272
+ ["Tell me a fun fact!"],
273
+ ["How do I stay productive?"]
274
+ ]
275
+ )
276
+
277
+ # Quick action buttons
278
+ with gr.Row():
279
+ clear_btn = gr.Button(
280
+ value="🗑️ New Chat",
281
+ variant="secondary",
282
+ size="sm",
283
+ elem_classes=["action-btn"]
284
+ )
285
+ retry_btn = gr.Button(
286
+ value="🔄 Retry",
287
+ variant="secondary",
288
+ size="sm",
289
+ elem_classes=["action-btn"]
290
+ )
291
+ download_btn = gr.Button(
292
+ value="💾 Download Chat",
293
+ variant="secondary",
294
+ size="sm",
295
+ elem_classes=["action-btn"]
296
+ )
297
+
298
+ # Chat input area
299
+ with gr.Row():
300
+ msg_input = gr.Textbox(
301
+ placeholder="Send a message to your AI assistant...",
302
+ label=None,
303
+ show_label=False,
304
+ lines=3,
305
+ max_lines=6,
306
+ submit_btn=True,
307
+ stop_btn=False,
308
+ scale=5,
309
+ elem_classes=["message-input"]
310
+ )
311
+
312
+ # Invisible submit button for better UX
313
+ submit_btn = gr.Button(
314
+ value="Send",
315
+ variant="primary",
316
+ size="lg",
317
+ visible=False # Hidden, we use Enter key
318
+ )
319
+
320
+ # Status indicator
321
+ status = gr.Textbox(
322
+ value="Ready to chat!",
323
+ label=None,
324
+ show_label=False,
325
+ interactive=False,
326
+ visible=False
327
+ )
328
+
329
+ # Event handlers
330
+ def handle_submit(message: str, history: List[List[str]]) -> List[List[str]]:
331
+ """Handle message submission."""
332
+ if not message.strip():
333
+ return history, status.update(value="Please enter a message...")
334
+
335
+ # Generate streaming response
336
+ for updated_history in streaming_response(message, history):
337
+ yield updated_history, status.update(value="Generating response...")
338
+
339
+ yield history, status.update(value="Ready to chat!")
340
+
341
+ def handle_clear() -> List[List[str]]:
342
+ """Clear the chat."""
343
+ return []
344
+
345
+ def handle_retry(message: str, history: List[List[str]]) -> List[List[str]]:
346
+ """Retry the last response."""
347
+ if not history:
348
+ return history, status.update(value="No messages to retry.")
349
+
350
+ return retry_response(message, history), status.update(value="Retrying...")
351
+
352
+ def format_chat_for_download(history: List[List[str]]) -> str:
353
+ """Format chat history for download."""
354
+ if not history:
355
+ return "No chat history to export."
356
+
357
+ formatted = "=" * 50 + "\n"
358
+ formatted += "ChatGPT Clone - Chat History\n"
359
+ formatted += "=" * 50 + "\n\n"
360
+
361
+ for i, (user_msg, bot_msg) in enumerate(history, 1):
362
+ formatted += f"[Message {i}]\n"
363
+ formatted += f"👤 You: {user_msg}\n"
364
+ formatted += f"🤖 Bot: {bot_msg}\n"
365
+ formatted += "-" * 30 + "\n\n"
366
+
367
+ formatted += "=" * 50 + "\n"
368
+ formatted += f"Total messages: {len(history)}\n"
369
+ formatted += "=" * 50 + "\n"
370
+
371
+ return formatted
372
+
373
+ def handle_download(history: List[List[str]]) -> str:
374
+ """Create downloadable chat history."""
375
+ return format_chat_for_download(history)
376
+
377
+ # Connect events
378
+ msg_input.submit(
379
+ fn=handle_submit,
380
+ inputs=[msg_input, chatbot],
381
+ outputs=[chatbot, status]
382
+ )
383
+
384
+ submit_btn.click(
385
+ fn=handle_submit,
386
+ inputs=[msg_input, chatbot],
387
+ outputs=[chatbot, status]
388
+ )
389
+
390
+ clear_btn.click(
391
+ fn=handle_clear,
392
+ inputs=None,
393
+ outputs=chatbot
394
+ )
395
+
396
+ retry_btn.click(
397
+ fn=handle_retry,
398
+ inputs=[msg_input, chatbot],
399
+ outputs=[chatbot, status]
400
+ )
401
+
402
+ download_btn.click(
403
+ fn=handle_download,
404
+ inputs=chatbot,
405
+ outputs=msg_input
406
+ )
407
+
408
+ return demo
409
+
410
+
411
+ # Create and launch the application
412
+ if __name__ == "__main__":
413
+ demo = create_chat_app()
414
+
415
+ # Launch with Gradio 6 syntax - all parameters in launch()
416
+ demo.launch(
417
+ theme=gr.themes.Soft(
418
+ primary_hue="teal",
419
+ secondary_hue="emerald",
420
+ neutral_hue="slate",
421
+ font=gr.themes.GoogleFont("Inter"),
422
+ text_size="lg",
423
+ spacing_size="lg",
424
+ radius_size="md"
425
+ ).set(
426
+ button_primary_background_fill="*primary_600",
427
+ button_primary_background_fill_hover="*primary_700",
428
+ button_secondary_background_fill="#f4f4f5",
429
+ button_secondary_background_fill_hover="#e4e4e7",
430
+ block_title_text_weight="600",
431
+ block_background_fill="white",
432
+ block_label_background_fill="*primary_100",
433
+ input_background_fill="white",
434
+ ),
435
+ css=custom_css,
436
+ footer_links=[
437
+ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
438
+ {"label": "Gradio", "url": "https://gradio.app"},
439
+ {"label": "Hugging Face", "url": "https://huggingface.co"}
440
+ ],
441
+ height=800,
442
+ inline=True,
443
+ inbrowser=True,
444
+ show_error=True
445
+ )
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=6.0
2
+ requests
3
+ Pillow
4
+ aiohttp
5
+ httpx
6
+ pydantic
7
+ python-multipart
8
+ websockets
9
+ fastapi
10
+ uvicorn