prernajeet14 commited on
Commit
bcddf76
·
verified ·
1 Parent(s): 7186a04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -415
app.py CHANGED
@@ -1,415 +0,0 @@
1
-
2
- def call_claude(self, prompt: str, max_tokens: int = 8000) -> str:
3
- """Call Claude 3 Haiku via AWS Bedrock with increased token limit."""
4
- if not self.bedrock_client:
5
- return "❌ **Error**: AWS Bedrock client not initialized. Please check your credentials."
6
-
7
- try:
8
- body = {
9
- "anthropic_version": "bedrock-2023-05-31",
10
- "max_tokens": max_tokens,
11
- "messages": [{"role": "user", "content": prompt}],
12
- "temperature": 0.1,
13
- "top_p": 0.9,
14
- }
15
-
16
- response = self.bedrock_client.invoke_model(
17
- modelId="anthropic.claude-3-haiku-20240307-v1:0",
18
- contentType='application/json',
19
- accept='application/json',
20
- body=json.dumps(body)
21
- )
22
-
23
- response_body = json.loads(response['body'].read())
24
- return response_body['content'][0]['text']
25
-
26
- except Exception as e:
27
- return f"❌ **Error calling Claude**: {str(e)}"
28
-
29
- def read_python_file(self, file_path: str) -> str:
30
- """Read content from a Python file."""
31
- try:
32
- with open(file_path, 'r', encoding='utf-8') as f:
33
- return f.read()
34
- except Exception as e:
35
- return f"Error reading file: {str(e)}"
36
-
37
- def read_notebook_file(self, file_path: str) -> str:
38
- """Read and extract code from a Jupyter notebook file."""
39
- try:
40
- with open(file_path, 'r', encoding='utf-8') as f:
41
- nb = nbformat.read(f, as_version=4)
42
-
43
- code_cells = []
44
- for cell in nb.cells:
45
- if cell.cell_type == 'code':
46
- code_cells.append(f"# Cell {len(code_cells) + 1}")
47
- code_cells.append(cell.source)
48
- code_cells.append("")
49
-
50
- return '\n'.join(code_cells)
51
- except Exception as e:
52
- return f"Error reading notebook: {str(e)}"
53
-
54
- def process_files(self, files: List) -> Tuple[str, str]:
55
- """Process uploaded files and return combined content."""
56
- if not files:
57
- return "", "No files uploaded"
58
-
59
- all_content = []
60
- file_info = []
61
-
62
- for file in files:
63
- file_path = file.name
64
- file_name = os.path.basename(file_path)
65
- file_extension = os.path.splitext(file_path)[1].lower()
66
-
67
- if file_extension == '.py':
68
- content = self.read_python_file(file_path)
69
- elif file_extension == '.ipynb':
70
- content = self.read_notebook_file(file_path)
71
- else:
72
- continue
73
-
74
- if content and not content.startswith("Error"):
75
- all_content.append(f"# 📁 File: {file_name}")
76
- all_content.append(f"# 📄 Type: {file_extension}")
77
- all_content.append("# " + "="*50)
78
- all_content.append(content)
79
- all_content.append("\n" + "="*60 + "\n")
80
- file_info.append(f"{file_name}")
81
-
82
- combined_content = '\n'.join(all_content)
83
- status = f"✅ Successfully loaded {len(file_info)} files: {', '.join(file_info)}"
84
-
85
- return combined_content, status
86
-
87
- def extract_code_blocks(self, text: str) -> List[str]:
88
- """Extract code blocks from response text."""
89
- code_blocks = re.findall(r'```(?:\w+)?\n(.*?)\n```', text, re.DOTALL)
90
- return code_blocks
91
-
92
- def create_download_file(self, content: str, filename: str = "generated_code.py") -> str:
93
- """Create a downloadable file with the given content."""
94
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
95
- base_name = os.path.splitext(filename)[0]
96
- extension = os.path.splitext(filename)[1] or '.py'
97
- filename = f"{base_name}_{timestamp}{extension}"
98
-
99
- temp_file = tempfile.NamedTemporaryFile(mode='w', suffix=extension, delete=False)
100
- temp_file.write(content)
101
- temp_file.close()
102
-
103
- return temp_file.name
104
-
105
- def process_message(self, message: str, files: List = None, history: List = None) -> Tuple[str, Optional[str]]:
106
- """Process user message and return response with optional download file."""
107
- if history is None:
108
- history = []
109
-
110
- # Process files if provided
111
- file_content = ""
112
- file_status = ""
113
- if files:
114
- file_content, file_status = self.process_files(files)
115
-
116
- # Detect continuation requests
117
- continue_keywords = ['continue', 'continue the code', 'continue from where', 'keep going', 'add more', 'extend', 'complete the']
118
- is_continuation = any(keyword in message.lower() for keyword in continue_keywords)
119
-
120
- # Build comprehensive context from history
121
- context = ""
122
- if history:
123
- if is_continuation:
124
- context = "\n\nFull conversation context for continuation:\n"
125
- for i, (user_msg, assistant_msg) in enumerate(history[-5:]):
126
- context += f"Exchange {i+1}:\nUser: {user_msg}\nAssistant: {assistant_msg}\n\n"
127
- else:
128
- context = "\n\nRecent conversation context:\n"
129
- for i, (user_msg, assistant_msg) in enumerate(history[-3:]):
130
- context += f"User: {user_msg}\nAssistant: {assistant_msg}\n\n"
131
-
132
- # Build specialized prompts based on request type
133
- if is_continuation:
134
- continuation_instructions = """CRITICAL INSTRUCTIONS FOR CONTINUATION:
135
- 1. Look at the previous conversation to understand what code was generated
136
- 2. Continue from where the previous code left off - DO NOT start from the beginning
137
- 3. Maintain the same coding style, structure, and patterns
138
- 4. Add new functionality or complete incomplete sections
139
- 5. Generate substantial code (aim for 500-2000+ lines if needed)
140
- 6. Ensure the continuation integrates seamlessly with previous code"""
141
-
142
- file_content_section = f"\nCode files content for reference:\n```\n{file_content}\n```" if file_content else ""
143
-
144
- final_instruction = "Based on the previous conversation, continue the code generation. Do NOT restart - pick up exactly where the previous response left off and continue building upon it. Provide substantial, complete code sections."
145
-
146
- prompt = f"""You are an advanced coding assistant. The user is asking you to CONTINUE or EXTEND previous code.
147
-
148
- {continuation_instructions}
149
-
150
- User's continuation request: {message}
151
-
152
- {file_status}
153
-
154
- {file_content_section}
155
-
156
- {context}
157
-
158
- {final_instruction}"""
159
-
160
- else:
161
- generation_keywords = ['create', 'generate', 'build', 'make', 'develop', 'write code', 'implement', 'design']
162
- is_generation = any(keyword in message.lower() for keyword in generation_keywords)
163
-
164
- if is_generation:
165
- generation_instructions = """CRITICAL INSTRUCTIONS FOR CODE GENERATION:
166
- 1. Generate COMPLETE, COMPREHENSIVE code - aim for 500-3000+ lines when appropriate
167
- 2. Include ALL necessary components: classes, functions, error handling, documentation
168
- 3. Create fully functional, production-ready applications
169
- 4. Add comprehensive comments and docstrings
170
- 5. Include proper imports, dependencies, and structure
171
- 6. Don't truncate or abbreviate - provide the FULL implementation
172
- 7. If the project is large, focus on core functionality but make it complete"""
173
-
174
- file_content_section = f"\nReference code files:\n```\n{file_content}\n```" if file_content else ""
175
-
176
- final_instruction = "Generate comprehensive, complete code that fully implements the requested functionality. Provide extensive code with proper structure, documentation, and all necessary components."
177
-
178
- prompt = f"""You are an advanced coding assistant specialized in generating comprehensive, production-ready code.
179
-
180
- {generation_instructions}
181
-
182
- User's request: {message}
183
-
184
- {file_status}
185
-
186
- {file_content_section}
187
-
188
- {context}
189
-
190
- {final_instruction}"""
191
-
192
- else:
193
- file_content_section = f"\nCode files content:\n```\n{file_content}\n```" if file_content else ""
194
-
195
- prompt = f"""You are an advanced coding assistant. Provide detailed, comprehensive responses.
196
-
197
- User's request: {message}
198
-
199
- {file_status}
200
-
201
- {file_content_section}
202
-
203
- {context}
204
-
205
- Provide a thorough and helpful response. If suggesting code changes, provide complete implementations."""
206
-
207
- # Get response from Claude
208
- response = self.call_claude(prompt, max_tokens=8000)
209
-
210
- # Extract code blocks for download
211
- code_blocks = self.extract_code_blocks(response)
212
- download_file = None
213
-
214
- if code_blocks:
215
- combined_code = "\n\n".join(code_blocks)
216
- if len(combined_code.strip()) > 50: # Only create download if substantial code
217
- download_file = self.create_download_file(combined_code)
218
-
219
- return response, download_file
220
-
221
- # Initialize the copilot
222
- copilot = CodingCopilot()
223
-
224
- # Fixed Desktop Layout CSS
225
- desktop_css = """
226
- /* Force desktop layout */
227
- .gradio-container {
228
- max-width: none !important;
229
- width: 100vw !important;
230
- height: 100vh !important;
231
- background: #0a0a0a !important;
232
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif !important;
233
- color: #ffffff !important;
234
- padding: 1rem !important;
235
- box-sizing: border-box !important;
236
- overflow: hidden !important;
237
- }
238
-
239
- /* Header Styles */
240
- .header-container {
241
- background: linear-gradient(135deg, #1a1a1a 0%, #2d1b1b 50%, #1a1a1a 100%) !important;
242
- border: 1px solid #dc2626 !important;
243
- border-radius: 16px !important;
244
- padding: 1.5rem !important;
245
- margin-bottom: 1rem !important;
246
- box-shadow: 0 8px 32px rgba(220, 38, 38, 0.15) !important;
247
- text-align: center !important;
248
- }
249
-
250
- .header-title {
251
- color: #ffffff !important;
252
- font-size: 2.2rem !important;
253
- font-weight: 700 !important;
254
- margin: 0 !important;
255
- background: linear-gradient(135deg, #ffffff 0%, #dc2626 100%) !important;
256
- -webkit-background-clip: text !important;
257
- -webkit-text-fill-color: transparent !important;
258
- background-clip: text !important;
259
- }
260
-
261
- .header-subtitle {
262
- color: #a1a1aa !important;
263
- font-size: 1rem !important;
264
- margin: 0.5rem 0 0 0 !important;
265
- font-weight: 400 !important;
266
- }
267
-
268
- /* FORCE DESKTOP LAYOUT - Critical CSS */
269
- .desktop-layout {
270
- display: flex !important;
271
- flex-direction: row !important;
272
- gap: 1.5rem !important;
273
- height: calc(100vh - 200px) !important;
274
- width: 100% !important;
275
- align-items: stretch !important;
276
- min-height: 600px !important;
277
- }
278
-
279
- /* Force sidebar to stay on left */
280
- .desktop-sidebar {
281
- background: linear-gradient(180deg, #1a1a1a 0%, #0f0f0f 100%) !important;
282
- border: 1px solid #dc2626 !important;
283
- border-radius: 16px !important;
284
- padding: 1.5rem !important;
285
- width: 320px !important;
286
- min-width: 320px !important;
287
- max-width: 320px !important;
288
- flex-shrink: 0 !important;
289
- flex-grow: 0 !important;
290
- box-shadow: 0 8px 32px rgba(220, 38, 38, 0.1) !important;
291
- overflow-y: auto !important;
292
- height: 100% !important;
293
- }
294
-
295
- /* Force chat to stay on right and take remaining space */
296
- .desktop-chat {
297
- background: linear-gradient(180deg, #111111 0%, #0a0a0a 100%) !important;
298
- border: 1px solid #262626 !important;
299
- border-radius: 16px !important;
300
- flex: 1 !important;
301
- flex-grow: 1 !important;
302
- flex-shrink: 1 !important;
303
- display: flex !important;
304
- flex-direction: column !important;
305
- overflow: hidden !important;
306
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
307
- height: 100% !important;
308
- min-width: 0 !important;
309
- }
310
-
311
- /* Override Gradio's column behavior */
312
- .desktop-layout > .block:first-child {
313
- width: 320px !important;
314
- min-width: 320px !important;
315
- max-width: 320px !important;
316
- flex: none !important;
317
- }
318
-
319
- .desktop-layout > .block:last-child {
320
- flex: 1 !important;
321
- min-width: 0 !important;
322
- }
323
-
324
- /* Sidebar content */
325
- .sidebar-section {
326
- margin-bottom: 1.5rem !important;
327
- }
328
-
329
- .sidebar-title {
330
- color: #dc2626 !important;
331
- font-weight: 700 !important;
332
- font-size: 1.1rem !important;
333
-
334
-
335
-
336
-
337
-
338
-
339
-
340
- # Event handlers
341
- def handle_submit(message, files, history):
342
- result = process_chat_message(message, files, history)
343
- return result
344
-
345
- # Quick actions
346
- quick_review.click(
347
- lambda: "Please perform a comprehensive code review of the uploaded files. Analyze code quality, identify potential bugs, suggest performance improvements, check for security vulnerabilities, and provide detailed recommendations with examples.",
348
- outputs=msg
349
- )
350
-
351
- quick_debug.click(
352
- lambda: "Please debug the uploaded code thoroughly. Identify any errors, bugs, logical issues, or potential runtime problems. Provide detailed explanations and complete fixed versions of the code.",
353
- outputs=msg
354
- )
355
-
356
- quick_optimize.click(
357
- lambda: "Please optimize the uploaded code for better performance, memory usage, and readability. Provide the complete optimized version with explanations of the improvements made.",
358
- outputs=msg
359
- )
360
-
361
- quick_explain.click(
362
- lambda: "Please provide a detailed explanation of the uploaded code. Break down its functionality, explain the algorithms used, document all functions and classes, and create comprehensive documentation.",
363
- outputs=msg
364
- )
365
-
366
- quick_generate.click(
367
- lambda: "Please generate a complete, production-ready application based on the requirements. Include all necessary components, error handling, documentation, and best practices.",
368
- outputs=msg
369
- )
370
-
371
- quick_test.click(
372
- lambda: "Please create comprehensive unit tests for the uploaded code. Include test cases for all functions, edge cases, error handling, and integration tests where applicable.",
373
- outputs=msg
374
- )
375
-
376
- # Main functionality
377
- submit.click(
378
- handle_submit,
379
- inputs=[msg, files, chat_history],
380
- outputs=[chatbot, chat_history, msg, download_file, download_status]
381
- ).then(
382
- lambda: None,
383
- outputs=files
384
- )
385
-
386
- msg.submit(
387
- handle_submit,
388
- inputs=[msg, files, chat_history],
389
- outputs=[chatbot, chat_history, msg, download_file, download_status]
390
- ).then(
391
- lambda: None,
392
- outputs=files
393
- )
394
-
395
- clear.click(
396
- clear_chat,
397
- outputs=[chatbot, chat_history, download_file, download_status]
398
- )
399
-
400
- # Footer
401
- gr.HTML("""
402
- <div class="footer">
403
- <p><strong>🚀 CODING COPILOT PRO</strong> • Professional Development Assistant</p>
404
- <p>Upload your code files and start building • Advanced AI • Secure & Private</p>
405
- </div>
406
- """)
407
-
408
- # Launch the app
409
- if __name__ == "__main__":
410
- app.launch(
411
- server_name="0.0.0.0",
412
- server_port=7860,
413
- share=True,
414
- show_error=True
415
- )