NeoPy commited on
Commit
ff50e88
·
verified ·
1 Parent(s): 3efa9ef

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +365 -0
  2. requirements.txt +12 -0
app.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ import os
4
+
5
+ # Initialize the client
6
+ client = InferenceClient(
7
+ model="deepseek-ai/DeepSeek-R1-0528-Qwen3-8B",
8
+ token=os.getenv("HF_TOKEN")
9
+ )
10
+
11
+ # Default system prompts
12
+ SYSTEM_PROMPTS = {
13
+ "Default Assistant": "You are a helpful, harmless, and honest AI assistant. Provide clear, accurate, and thoughtful responses.",
14
+ "Creative Writer": "You are a creative writing assistant. Help users with storytelling, poetry, and imaginative content. Be expressive and artistic.",
15
+ "Code Helper": "You are an expert programmer. Help users write, debug, and understand code. Provide clear explanations and best practices.",
16
+ "Socratic Teacher": "You are a Socratic teacher. Instead of giving direct answers, guide users to discover answers through thoughtful questions.",
17
+ "Friendly Chat": "You are a friendly conversational partner. Be warm, engaging, and personable. Use casual language and show genuine interest.",
18
+ "Custom": ""
19
+ }
20
+
21
+ def format_thinking(content):
22
+ """Format thinking tags for display"""
23
+ if "" in content:
24
+ parts = content.split("" in part:
25
+ think_content, rest = part.split("", 1)
26
+ formatted += f"\n\n<details><summary>💭 Thinking Process</summary>\n\n{think_content.strip()}\n\n</details>\n\n{rest}"
27
+ else:
28
+ formatted += part
29
+ return formatted
30
+ return content
31
+
32
+ def chat(message, history, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking):
33
+ """Main chat function with streaming support"""
34
+
35
+ # Determine system prompt
36
+ if system_prompt_choice == "Custom":
37
+ system_content = custom_system_prompt if custom_system_prompt.strip() else SYSTEM_PROMPTS["Default Assistant"]
38
+ else:
39
+ system_content = SYSTEM_PROMPTS.get(system_prompt_choice, SYSTEM_PROMPTS["Default Assistant"])
40
+
41
+ # Build messages
42
+ messages = [{"role": "system", "content": system_content}]
43
+
44
+ # Add history
45
+ for msg in history:
46
+ if msg["role"] == "user":
47
+ messages.append({"role": "user", "content": msg["content"]})
48
+ elif msg["role"] == "assistant":
49
+ # Clean up thinking tags from history
50
+ content = msg["content"]
51
+ if "<details>" in content:
52
+ # Remove the formatted thinking for API calls
53
+ import re
54
+ content = re.sub(r'<details>.*?</details>', '', content, flags=re.DOTALL)
55
+ messages.append({"role": "assistant", "content": content.strip()})
56
+
57
+ # Add current message
58
+ messages.append({"role": "user", "content": message})
59
+
60
+ try:
61
+ response = ""
62
+ stream = client.chat_completion(
63
+ messages=messages,
64
+ max_tokens=max_tokens,
65
+ temperature=temperature,
66
+ top_p=top_p,
67
+ stream=True
68
+ )
69
+
70
+ for chunk in stream:
71
+ if chunk.choices[0].delta.content:
72
+ response += chunk.choices[0].delta.content
73
+ # Format thinking if enabled
74
+ if show_thinking:
75
+ yield format_thinking(response)
76
+ else:
77
+ # Hide thinking content
78
+ display_response = response
79
+ if "" in display_response:
80
+ import re
81
+ display_response = re.sub(r'', '', display_response, flags=re.DOTALL)
82
+ else:
83
+ # Still thinking, show placeholder
84
+ display_response = "🤔 *Thinking...*"
85
+ yield display_response.strip()
86
+
87
+ except Exception as e:
88
+ yield f"❌ Error: {str(e)}\n\nPlease check your HF_TOKEN and try again."
89
+
90
+ def clear_chat():
91
+ """Clear the chat history"""
92
+ return [], ""
93
+
94
+ def export_chat(history):
95
+ """Export chat history as text"""
96
+ if not history:
97
+ return "No chat history to export."
98
+
99
+ export_text = "# Chat Export\n\n"
100
+ for msg in history:
101
+ role = "👤 User" if msg["role"] == "user" else "🤖 Assistant"
102
+ export_text += f"## {role}\n{msg['content']}\n\n---\n\n"
103
+
104
+ return export_text
105
+
106
+ # Custom CSS
107
+ css = """
108
+ .header-container {
109
+ text-align: center;
110
+ padding: 20px;
111
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
112
+ border-radius: 12px;
113
+ margin-bottom: 20px;
114
+ }
115
+ .header-container h1 {
116
+ color: white;
117
+ margin: 0;
118
+ font-size: 2em;
119
+ }
120
+ .header-container p {
121
+ color: rgba(255,255,255,0.9);
122
+ margin: 10px 0 0 0;
123
+ }
124
+ .header-container a {
125
+ color: #ffd700;
126
+ text-decoration: none;
127
+ font-weight: bold;
128
+ }
129
+ .header-container a:hover {
130
+ text-decoration: underline;
131
+ }
132
+ .parameter-box {
133
+ background: var(--background-fill-secondary);
134
+ padding: 15px;
135
+ border-radius: 8px;
136
+ margin-top: 10px;
137
+ }
138
+ .chatbot-container {
139
+ min-height: 500px;
140
+ }
141
+ footer {
142
+ text-align: center;
143
+ margin-top: 20px;
144
+ padding: 10px;
145
+ color: var(--body-text-color-subdued);
146
+ }
147
+ """
148
+
149
+ # Build the interface
150
+ with gr.Blocks(
151
+ title="DeepSeek R1 Chatbot",
152
+ theme=gr.themes.Soft(),
153
+ css=css,
154
+ fill_height=True,
155
+ footer_links=[
156
+ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
157
+ {"label": "Model", "url": "https://huggingface.co/deepseek-ai/DeepSeek-R1-0528-Qwen3-8B"}
158
+ ]
159
+ ) as demo:
160
+
161
+ # Header
162
+ gr.HTML("""
163
+ <div class="header-container">
164
+ <h1>🧠 DeepSeek R1 Chatbot</h1>
165
+ <p>Powered by DeepSeek-R1-0528-Qwen3-8B with reasoning capabilities</p>
166
+ <p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">Built with anycoder</a></p>
167
+ </div>
168
+ """)
169
+
170
+ with gr.Row():
171
+ # Main chat column
172
+ with gr.Column(scale=3):
173
+ chatbot = gr.Chatbot(
174
+ label="Chat",
175
+ height=500,
176
+ type="messages",
177
+ show_copy_button=True,
178
+ avatar_images=(None, "https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.svg"),
179
+ render_markdown=True,
180
+ elem_classes=["chatbot-container"]
181
+ )
182
+
183
+ with gr.Row():
184
+ msg = gr.Textbox(
185
+ placeholder="Type your message here... (Press Enter to send)",
186
+ label="Message",
187
+ scale=4,
188
+ lines=2,
189
+ max_lines=5,
190
+ autofocus=True
191
+ )
192
+ send_btn = gr.Button("Send 📤", variant="primary", scale=1)
193
+
194
+ with gr.Row():
195
+ clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary")
196
+ regenerate_btn = gr.Button("🔄 Regenerate", variant="secondary")
197
+ export_btn = gr.Button("📥 Export", variant="secondary")
198
+
199
+ # Settings sidebar
200
+ with gr.Column(scale=1):
201
+ gr.Markdown("### ⚙️ Settings")
202
+
203
+ with gr.Accordion("System Prompt", open=True):
204
+ system_prompt_choice = gr.Dropdown(
205
+ choices=list(SYSTEM_PROMPTS.keys()),
206
+ value="Default Assistant",
207
+ label="Preset Prompts",
208
+ interactive=True
209
+ )
210
+
211
+ custom_system_prompt = gr.Textbox(
212
+ label="Custom System Prompt",
213
+ placeholder="Enter your custom system prompt here...",
214
+ lines=4,
215
+ visible=False
216
+ )
217
+
218
+ with gr.Accordion("Generation Parameters", open=False):
219
+ temperature = gr.Slider(
220
+ minimum=0.0,
221
+ maximum=2.0,
222
+ value=0.7,
223
+ step=0.1,
224
+ label="Temperature",
225
+ info="Higher = more creative, Lower = more focused"
226
+ )
227
+
228
+ max_tokens = gr.Slider(
229
+ minimum=64,
230
+ maximum=4096,
231
+ value=1024,
232
+ step=64,
233
+ label="Max Tokens",
234
+ info="Maximum response length"
235
+ )
236
+
237
+ top_p = gr.Slider(
238
+ minimum=0.0,
239
+ maximum=1.0,
240
+ value=0.9,
241
+ step=0.05,
242
+ label="Top P",
243
+ info="Nucleus sampling parameter"
244
+ )
245
+
246
+ with gr.Accordion("Display Options", open=False):
247
+ show_thinking = gr.Checkbox(
248
+ value=True,
249
+ label="Show Thinking Process",
250
+ info="Display the model's reasoning steps"
251
+ )
252
+
253
+ # Export output
254
+ export_output = gr.Textbox(
255
+ label="Exported Chat",
256
+ lines=10,
257
+ visible=False,
258
+ show_copy_button=True
259
+ )
260
+
261
+ # Examples
262
+ gr.Markdown("### 💡 Example Prompts")
263
+ gr.Examples(
264
+ examples=[
265
+ ["Explain quantum computing in simple terms"],
266
+ ["Write a haiku about artificial intelligence"],
267
+ ["What's the time complexity of quicksort and why?"],
268
+ ["Help me brainstorm ideas for a sustainable business"],
269
+ ["Solve this step by step: If 3x + 7 = 22, what is x?"],
270
+ ],
271
+ inputs=msg,
272
+ label=""
273
+ )
274
+
275
+ # Event handlers
276
+ def toggle_custom_prompt(choice):
277
+ return gr.Textbox(visible=(choice == "Custom"))
278
+
279
+ system_prompt_choice.change(
280
+ toggle_custom_prompt,
281
+ inputs=[system_prompt_choice],
282
+ outputs=[custom_system_prompt]
283
+ )
284
+
285
+ def user_message(message, history):
286
+ if message.strip():
287
+ history.append({"role": "user", "content": message})
288
+ return "", history
289
+
290
+ def bot_response(history, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking):
291
+ if not history:
292
+ yield history
293
+ return
294
+
295
+ user_msg = history[-1]["content"]
296
+ history_for_api = history[:-1]
297
+
298
+ history.append({"role": "assistant", "content": ""})
299
+
300
+ for response in chat(user_msg, history_for_api, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking):
301
+ history[-1]["content"] = response
302
+ yield history
303
+
304
+ def regenerate(history, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking):
305
+ if len(history) >= 2:
306
+ # Remove last assistant message
307
+ history = history[:-1]
308
+ # Get last user message
309
+ user_msg = history[-1]["content"]
310
+ history_for_api = history[:-1]
311
+
312
+ history.append({"role": "assistant", "content": ""})
313
+
314
+ for response in chat(user_msg, history_for_api, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking):
315
+ history[-1]["content"] = response
316
+ yield history
317
+ else:
318
+ yield history
319
+
320
+ def show_export(history):
321
+ export_text = export_chat(history)
322
+ return gr.Textbox(visible=True, value=export_text)
323
+
324
+ # Wire up events
325
+ msg.submit(
326
+ user_message,
327
+ inputs=[msg, chatbot],
328
+ outputs=[msg, chatbot],
329
+ queue=False
330
+ ).then(
331
+ bot_response,
332
+ inputs=[chatbot, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking],
333
+ outputs=[chatbot]
334
+ )
335
+
336
+ send_btn.click(
337
+ user_message,
338
+ inputs=[msg, chatbot],
339
+ outputs=[msg, chatbot],
340
+ queue=False
341
+ ).then(
342
+ bot_response,
343
+ inputs=[chatbot, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking],
344
+ outputs=[chatbot]
345
+ )
346
+
347
+ clear_btn.click(
348
+ clear_chat,
349
+ outputs=[chatbot, msg]
350
+ )
351
+
352
+ regenerate_btn.click(
353
+ regenerate,
354
+ inputs=[chatbot, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p, show_thinking],
355
+ outputs=[chatbot]
356
+ )
357
+
358
+ export_btn.click(
359
+ show_export,
360
+ inputs=[chatbot],
361
+ outputs=[export_output]
362
+ )
363
+
364
+ if __name__ == "__main__":
365
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub
2
+ gradio
3
+ requests
4
+ Pillow
5
+ git+https://github.com/huggingface/transformers
6
+ torch
7
+ tokenizers
8
+ accelerate
9
+ numpy
10
+ pandas
11
+ sentencepiece
12
+ datasets