krisshattanicole commited on
Commit
01d7cb0
Β·
verified Β·
1 Parent(s): 52155e7

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +422 -0
app.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DeepSeek Coder Agent - HuggingFace Space
3
+ A cloud-based AI coding assistant powered by DeepSeek Coder V3
4
+ Replace local models with this cloud-hosted solution
5
+ """
6
+
7
+ import gradio as gr
8
+ import os
9
+ import requests
10
+ import json
11
+ from typing import Optional, Dict, Any
12
+ import base64
13
+ from datetime import datetime
14
+
15
+
16
+ class DeepSeekCoderAgent:
17
+ """DeepSeek Coder API Integration"""
18
+
19
+ def __init__(self, api_key: Optional[str] = None):
20
+ self.api_key = api_key or os.getenv("DEEPSEEK_API_KEY")
21
+ self.api_url = "https://api.deepseek.com/v1/chat/completions"
22
+ self.model = "deepseek-coder"
23
+ self.history = []
24
+
25
+ def chat(self, message: str, code_context: str = "", system_prompt: str = "") -> str:
26
+ """Send message to DeepSeek Coder API"""
27
+
28
+ if not self.api_key:
29
+ return "❌ Error: DeepSeek API key not configured. Please set DEEPSEEK_API_KEY environment variable or enter your API key in settings."
30
+
31
+ # Build messages
32
+ messages = []
33
+
34
+ # System prompt
35
+ if system_prompt:
36
+ messages.append({"role": "system", "content": system_prompt})
37
+ else:
38
+ messages.append({
39
+ "role": "system",
40
+ "content": """You are DeepSeek Coder Agent, an expert AI programming assistant.
41
+ You help with:
42
+ - Writing clean, efficient code in any language
43
+ - Debugging and fixing errors
44
+ - Explaining code and concepts
45
+ - Refactoring and optimization
46
+ - Code review and best practices
47
+ - Architecture and design patterns
48
+
49
+ Always provide clear, well-commented code examples."""
50
+ })
51
+
52
+ # Add code context if provided
53
+ if code_context:
54
+ messages.append({
55
+ "role": "user",
56
+ "content": f"Here's my current code context:\n```python\n{code_context}\n```\n\nPlease help me with this code."
57
+ })
58
+
59
+ # Add user message
60
+ messages.append({"role": "user", "content": message})
61
+
62
+ # Add conversation history
63
+ messages.extend(self.history[-10:]) # Last 10 messages for context
64
+
65
+ try:
66
+ headers = {
67
+ "Content-Type": "application/json",
68
+ "Authorization": f"Bearer {self.api_key}"
69
+ }
70
+
71
+ payload = {
72
+ "model": self.model,
73
+ "messages": messages,
74
+ "temperature": 0.7,
75
+ "max_tokens": 4096,
76
+ "stream": False
77
+ }
78
+
79
+ response = requests.post(
80
+ self.api_url,
81
+ headers=headers,
82
+ json=payload,
83
+ timeout=60
84
+ )
85
+
86
+ if response.status_code == 200:
87
+ result = response.json()
88
+ assistant_message = result["choices"][0]["message"]["content"]
89
+
90
+ # Update history
91
+ self.history.append({"role": "user", "content": message})
92
+ self.history.append({"role": "assistant", "content": assistant_message})
93
+
94
+ return assistant_message
95
+ else:
96
+ return f"❌ API Error: {response.status_code}\n{response.text}"
97
+
98
+ except requests.exceptions.Timeout:
99
+ return "⏱️ Request timed out. The model is taking longer than expected. Please try again."
100
+ except requests.exceptions.RequestException as e:
101
+ return f"❌ Network Error: {str(e)}"
102
+ except Exception as e:
103
+ return f"❌ Error: {str(e)}"
104
+
105
+ def clear_history(self):
106
+ """Clear conversation history"""
107
+ self.history = []
108
+
109
+ def get_stats(self) -> str:
110
+ """Get agent statistics"""
111
+ return f"""
112
+ **Session Stats:**
113
+ - Messages: {len(self.history) // 2}
114
+ - Model: {self.model}
115
+ - API Key: {'βœ…' if self.api_key else '❌'}
116
+ - Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
117
+ """
118
+
119
+
120
+ def create_code_completion(code: str, language: str, instruction: str, api_key: str) -> str:
121
+ """Generate code completion"""
122
+ agent = DeepSeekCoderAgent(api_key)
123
+
124
+ prompt = f"""Complete or improve this {language} code based on the instruction.
125
+
126
+ Instruction: {instruction}
127
+
128
+ Current Code:
129
+ ```{language}
130
+ {code}
131
+ ```
132
+
133
+ Provide the complete, working code with explanations:"""
134
+
135
+ return agent.chat(prompt)
136
+
137
+
138
+ def explain_code(code: str, language: str, api_key: str) -> str:
139
+ """Explain code functionality"""
140
+ agent = DeepSeekCoderAgent(api_key)
141
+
142
+ prompt = f"""Explain this {language} code in detail:
143
+
144
+ ```{language}
145
+ {code}
146
+ ```
147
+
148
+ Break down:
149
+ 1. What the code does
150
+ 2. Key functions/methods
151
+ 3. Logic flow
152
+ 4. Any potential issues or improvements"""
153
+
154
+ return agent.chat(prompt)
155
+
156
+
157
+ def debug_code(code: str, language: str, error_message: str, api_key: str) -> str:
158
+ """Debug code and find issues"""
159
+ agent = DeepSeekCoderAgent(api_key)
160
+
161
+ prompt = f"""Debug this {language} code:
162
+
163
+ ```{language}
164
+ {code}
165
+ ```
166
+
167
+ Error Message: {error_message if error_message else "No specific error message"}
168
+
169
+ Please:
170
+ 1. Identify the issue(s)
171
+ 2. Explain what's wrong
172
+ 3. Provide the fixed code
173
+ 4. Explain the fix"""
174
+
175
+ return agent.chat(prompt)
176
+
177
+
178
+ def generate_code_from_description(description: str, language: str, api_key: str) -> str:
179
+ """Generate code from natural language description"""
180
+ agent = DeepSeekCoderAgent(api_key)
181
+
182
+ prompt = f"""Write {language} code that does the following:
183
+
184
+ {description}
185
+
186
+ Requirements:
187
+ - Clean, readable code
188
+ - Proper error handling
189
+ - Comments explaining key parts
190
+ - Best practices for {language}
191
+
192
+ Provide the complete implementation:"""
193
+
194
+ return agent.chat(prompt)
195
+
196
+
197
+ def create_ui() -> gr.Blocks:
198
+ """Create the Gradio interface"""
199
+
200
+ with gr.Blocks(
201
+ title="DeepSeek Coder Agent",
202
+ theme=gr.themes.Soft(),
203
+ css="""
204
+ .gradio-container { max-width: 1400px !important; }
205
+ .code-editor { font-family: 'Fira Code', monospace; }
206
+ .chat-message { border-radius: 12px !important; }
207
+ """
208
+ ) as demo:
209
+
210
+ # Header
211
+ gr.Markdown("""
212
+ # πŸš€ DeepSeek Coder Agent
213
+
214
+ **Cloud-based AI coding assistant powered by DeepSeek Coder V3**
215
+
216
+ Replace local models with this hosted solution - no GPU required!
217
+
218
+ [Documentation](https://api-docs.deepseek.com/) | [Pricing](https://platform.deepseek.com/)
219
+ """)
220
+
221
+ # State
222
+ api_key_state = gr.State("")
223
+
224
+ with gr.Row():
225
+ # Left Sidebar - Settings & Tools
226
+ with gr.Column(scale=1, min_width=300):
227
+ gr.Markdown("### βš™οΈ Settings")
228
+
229
+ api_key_input = gr.Textbox(
230
+ label="DeepSeek API Key",
231
+ type="password",
232
+ placeholder="sk-...",
233
+ help_text="Get your API key from https://platform.deepseek.com/"
234
+ )
235
+
236
+ model_select = gr.Dropdown(
237
+ label="Model",
238
+ choices=["deepseek-coder", "deepseek-chat"],
239
+ value="deepseek-coder",
240
+ info="Select the DeepSeek model to use"
241
+ )
242
+
243
+ gr.Markdown("### πŸ› οΈ Quick Tools")
244
+
245
+ tool_select = gr.Radio(
246
+ choices=[
247
+ "πŸ’¬ Chat",
248
+ "✨ Code Completion",
249
+ "πŸ“– Explain Code",
250
+ "πŸ› Debug Code",
251
+ "🎨 Generate Code",
252
+ "πŸ”„ Refactor Code",
253
+ "πŸ“ Code Review"
254
+ ],
255
+ value="πŸ’¬ Chat",
256
+ label="Tool"
257
+ )
258
+
259
+ language_select = gr.Dropdown(
260
+ label="Programming Language",
261
+ choices=[
262
+ "Python", "JavaScript", "TypeScript", "Java", "C++", "C#",
263
+ "Go", "Rust", "Ruby", "PHP", "Swift", "Kotlin",
264
+ "SQL", "HTML/CSS", "Shell", "Other"
265
+ ],
266
+ value="Python",
267
+ interactive=True
268
+ )
269
+
270
+ gr.Markdown("### πŸ“Š Stats")
271
+ stats_output = gr.Markdown("**Status:** Ready")
272
+
273
+ clear_btn = gr.Button("πŸ—‘οΈ Clear History", variant="secondary")
274
+
275
+ # Main Content Area
276
+ with gr.Column(scale=3):
277
+ # Tool-specific inputs
278
+ with gr.Group(visible=True) as chat_group:
279
+ chat_input = gr.ChatInterface(
280
+ fn=lambda msg, history: handle_chat(msg, history, api_key_state),
281
+ type="messages",
282
+ height=500,
283
+ placeholder="Ask me anything about coding..."
284
+ )
285
+
286
+ with gr.Group(visible=False) as code_group:
287
+ code_input = gr.Code(
288
+ label="Code",
289
+ language="python",
290
+ lines=15,
291
+ placeholder="Paste your code here..."
292
+ )
293
+
294
+ instruction_input = gr.Textbox(
295
+ label="Instruction",
296
+ placeholder="What would you like me to do with this code?",
297
+ lines=3
298
+ )
299
+
300
+ error_input = gr.Textbox(
301
+ label="Error Message (optional)",
302
+ placeholder="Paste any error messages you're seeing...",
303
+ lines=2,
304
+ visible=False
305
+ )
306
+
307
+ run_btn = gr.Button("▢️ Run", variant="primary", size="lg")
308
+ code_output = gr.Code(label="Result", language="python", lines=20)
309
+
310
+ # Code generation input
311
+ with gr.Group(visible=False) as generate_group:
312
+ desc_input = gr.Textbox(
313
+ label="Describe what you want to build",
314
+ placeholder="E.g., 'A function that sorts a list using quicksort and handles edge cases'",
315
+ lines=4
316
+ )
317
+
318
+ generate_btn = gr.Button("✨ Generate Code", variant="primary", size="lg")
319
+ generate_output = gr.Code(label="Generated Code", language="python", lines=25)
320
+
321
+ # Footer
322
+ gr.Markdown("""
323
+ ---
324
+ **Powered by DeepSeek Coder V3** | Built for HuggingFace Spaces
325
+
326
+ πŸ’‘ **Tip:** You can delete local models after setting up this space. All processing happens in the cloud!
327
+ """)
328
+
329
+ # Event Handlers
330
+ def update_tool_ui(tool):
331
+ """Update UI based on selected tool"""
332
+ chat_vis = gr.update(visible=(tool == "πŸ’¬ Chat"))
333
+ code_vis = gr.update(visible=(tool != "πŸ’¬ Chat" and tool != "🎨 Generate Code"))
334
+ generate_vis = gr.update(visible=(tool == "🎨 Generate Code"))
335
+ error_vis = gr.update(visible=(tool == "πŸ› Debug Code"))
336
+
337
+ return chat_vis, code_vis, generate_vis, error_vis
338
+
339
+ def handle_chat(msg, history, api_key):
340
+ """Handle chat messages"""
341
+ agent = DeepSeekCoderAgent(api_key)
342
+ response = agent.chat(msg["content"])
343
+ return {"role": "assistant", "content": response}
344
+
345
+ def run_code_tool(code, instruction, error, tool, language, api_key):
346
+ """Run the selected code tool"""
347
+ if tool == "✨ Code Completion":
348
+ result = create_code_completion(code, language, instruction, api_key)
349
+ elif tool == "πŸ“– Explain Code":
350
+ result = explain_code(code, language, api_key)
351
+ elif tool == "πŸ› Debug Code":
352
+ result = debug_code(code, language, error, api_key)
353
+ elif tool == "πŸ”„ Refactor Code":
354
+ result = create_code_completion(code, language, f"Refactor this code: {instruction}", api_key)
355
+ elif tool == "πŸ“ Code Review":
356
+ result = create_code_completion(code, language, f"Review this code: {instruction}", api_key)
357
+ else:
358
+ result = "Please select a tool"
359
+
360
+ return result
361
+
362
+ def generate_from_desc(desc, language, api_key):
363
+ """Generate code from description"""
364
+ result = generate_code_from_description(desc, language, api_key)
365
+ return result
366
+
367
+ def update_stats(api_key):
368
+ """Update stats display"""
369
+ agent = DeepSeekCoderAgent(api_key)
370
+ return agent.get_stats()
371
+
372
+ # Wire up events
373
+ tool_select.change(
374
+ fn=update_tool_ui,
375
+ inputs=[tool_select],
376
+ outputs=[chat_group, code_group, generate_group, error_input]
377
+ )
378
+
379
+ api_key_input.change(
380
+ fn=lambda x: x,
381
+ inputs=[api_key_input],
382
+ outputs=[api_key_state]
383
+ ).then(
384
+ fn=update_stats,
385
+ inputs=[api_key_input],
386
+ outputs=[stats_output]
387
+ )
388
+
389
+ run_btn.click(
390
+ fn=run_code_tool,
391
+ inputs=[code_input, instruction_input, error_input, tool_select, language_select, api_key_input],
392
+ outputs=[code_output]
393
+ )
394
+
395
+ generate_btn.click(
396
+ fn=generate_from_desc,
397
+ inputs=[desc_input, language_select, api_key_input],
398
+ outputs=[generate_output]
399
+ )
400
+
401
+ clear_btn.click(
402
+ fn=lambda: None,
403
+ inputs=[],
404
+ outputs=[]
405
+ ).then(
406
+ fn=lambda: DeepSeekCoderAgent(api_key_state.value).clear_history(),
407
+ inputs=[],
408
+ outputs=[]
409
+ )
410
+
411
+ return demo
412
+
413
+
414
+ # Launch the app
415
+ if __name__ == "__main__":
416
+ demo = create_ui()
417
+ demo.launch(
418
+ server_name="0.0.0.0",
419
+ server_port=7860,
420
+ share=False,
421
+ show_error=True
422
+ )