BoobyBoobs commited on
Commit
6ddb7a6
Β·
verified Β·
1 Parent(s): c671a60

Deploy Gradio app with multiple files

Browse files
Files changed (2) hide show
  1. app.py +805 -0
  2. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import os
4
+ import re
5
+ import time
6
+ import uuid
7
+ from datetime import datetime
8
+ from typing import Dict, List, Tuple, Any, Optional
9
+ import subprocess
10
+ import tempfile
11
+ import shutil
12
+
13
+ class CodeExecutionEnvironment:
14
+ """Safe code execution environment with sandboxing"""
15
+
16
+ def __init__(self):
17
+ self.temp_dir = tempfile.mkdtemp()
18
+ self.history = []
19
+
20
+ def execute_code(self, code: str, language: str = "python") -> Dict[str, Any]:
21
+ """Execute code in a sandboxed environment"""
22
+ execution_id = str(uuid.uuid4())[:8]
23
+ timestamp = datetime.now().isoformat()
24
+
25
+ try:
26
+ if language.lower() == "python":
27
+ result = self._execute_python(code)
28
+ elif language.lower() == "javascript":
29
+ result = self._execute_javascript(code)
30
+ elif language.lower() == "bash":
31
+ result = self._execute_bash(code)
32
+ else:
33
+ result = {"output": f"Language {language} not supported", "error": True}
34
+
35
+ execution_record = {
36
+ "id": execution_id,
37
+ "timestamp": timestamp,
38
+ "code": code,
39
+ "language": language,
40
+ "result": result
41
+ }
42
+ self.history.append(execution_record)
43
+
44
+ return result
45
+
46
+ except Exception as e:
47
+ return {
48
+ "output": f"Execution error: {str(e)}",
49
+ "error": True,
50
+ "execution_id": execution_id
51
+ }
52
+
53
+ def _execute_python(self, code: str) -> Dict[str, Any]:
54
+ """Execute Python code safely"""
55
+ try:
56
+ # Create a temporary file
57
+ temp_file = os.path.join(self.temp_dir, f"temp_{uuid.uuid4()}.py")
58
+ with open(temp_file, 'w') as f:
59
+ f.write(code)
60
+
61
+ # Execute with timeout
62
+ result = subprocess.run(
63
+ ['python', temp_file],
64
+ capture_output=True,
65
+ text=True,
66
+ timeout=30,
67
+ cwd=self.temp_dir
68
+ )
69
+
70
+ return {
71
+ "output": result.stdout,
72
+ "error": result.returncode != 0,
73
+ "stderr": result.stderr if result.stderr else None
74
+ }
75
+ except subprocess.TimeoutExpired:
76
+ return {"output": "Code execution timed out (30s limit)", "error": True}
77
+ except Exception as e:
78
+ return {"output": f"Python execution error: {str(e)}", "error": True}
79
+
80
+ def _execute_javascript(self, code: str) -> Dict[str, Any]:
81
+ """Execute JavaScript code using Node.js"""
82
+ try:
83
+ temp_file = os.path.join(self.temp_dir, f"temp_{uuid.uuid4()}.js")
84
+ with open(temp_file, 'w') as f:
85
+ f.write(code)
86
+
87
+ result = subprocess.run(
88
+ ['node', temp_file],
89
+ capture_output=True,
90
+ text=True,
91
+ timeout=30,
92
+ cwd=self.temp_dir
93
+ )
94
+
95
+ return {
96
+ "output": result.stdout,
97
+ "error": result.returncode != 0,
98
+ "stderr": result.stderr if result.stderr else None
99
+ }
100
+ except subprocess.TimeoutExpired:
101
+ return {"output": "Code execution timed out (30s limit)", "error": True}
102
+ except FileNotFoundError:
103
+ return {"output": "Node.js not found. Please install Node.js to run JavaScript.", "error": True}
104
+ except Exception as e:
105
+ return {"output": f"JavaScript execution error: {str(e)}", "error": True}
106
+
107
+ def _execute_bash(self, code: str) -> Dict[str, Any]:
108
+ """Execute bash commands"""
109
+ try:
110
+ result = subprocess.run(
111
+ code,
112
+ shell=True,
113
+ capture_output=True,
114
+ text=True,
115
+ timeout=30,
116
+ cwd=self.temp_dir
117
+ )
118
+
119
+ return {
120
+ "output": result.stdout,
121
+ "error": result.returncode != 0,
122
+ "stderr": result.stderr if result.stderr else None
123
+ }
124
+ except subprocess.TimeoutExpired:
125
+ return {"output": "Command execution timed out (30s limit)", "error": True}
126
+ except Exception as e:
127
+ return {"output": f"Bash execution error: {str(e)}", "error": True}
128
+
129
+ def cleanup(self):
130
+ """Clean up temporary files"""
131
+ try:
132
+ shutil.rmtree(self.temp_dir)
133
+ except:
134
+ pass
135
+
136
+ class AICodeAssistant:
137
+ """AI-powered code generation and assistance"""
138
+
139
+ def __init__(self):
140
+ self.templates = {
141
+ "react": """import React from 'react';
142
+
143
+ function Component() {{
144
+ return (
145
+ <div>
146
+ <h1>Hello World</h1>
147
+ </div>
148
+ );
149
+ }}
150
+
151
+ export default Component;""",
152
+ "python": """def main():
153
+ print("Hello, World!")
154
+
155
+ if __name__ == "__main__":
156
+ main()""",
157
+ "fastapi": """from fastapi import FastAPI
158
+
159
+ app = FastAPI()
160
+
161
+ @app.get("/")
162
+ def read_root():
163
+ return {{"message": "Hello World"}}""",
164
+ "gradio": """import gradio as gr
165
+
166
+ def greet(name):
167
+ return f"Hello {name}!"
168
+
169
+ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
170
+ demo.launch()""",
171
+ "express": """const express = require('express');
172
+ const app = express();
173
+ const port = 3000;
174
+
175
+ app.get('/', (req, res) => {
176
+ res.json({ message: 'Hello World!' });
177
+ });
178
+
179
+ app.listen(port, () => {
180
+ console.log(`Server running at http://localhost:${port}`);
181
+ });""",
182
+ }
183
+
184
+ def generate_code(self, prompt: str, language: str, context: str = "") -> str:
185
+ """Generate code based on prompt and language"""
186
+ # Enhanced code generation with context awareness
187
+ language = language.lower()
188
+
189
+ # Check for template usage
190
+ if any(template in prompt.lower() for template in ["react", "component", "jsx"]):
191
+ return self.templates["react"]
192
+ elif "fastapi" in prompt.lower():
193
+ return self.templates["fastapi"]
194
+ elif "gradio" in prompt.lower():
195
+ return self.templates["gradio"]
196
+ elif "express" in prompt.lower():
197
+ return self.templates["express"]
198
+ elif "python" in prompt.lower() or language == "python":
199
+ return self.templates["python"]
200
+
201
+ # Generate code based on common patterns
202
+ if "function" in prompt.lower() or "def" in prompt.lower():
203
+ if language == "python":
204
+ return f"""def {prompt.split()[-1] if prompt.split() else 'function_name'}():
205
+ # TODO: Implement function
206
+ pass
207
+
208
+ # Example usage
209
+ if __name__ == "__main__":
210
+ result = {prompt.split()[-1] if prompt.split() else 'function_name'}()
211
+ print(result)"""
212
+ elif language in ["javascript", "js"]:
213
+ return f"""function {prompt.split()[-1] if prompt.split() else 'functionName'}() {{
214
+ // TODO: Implement function
215
+ console.log("Function called");
216
+ }}
217
+
218
+ // Example usage
219
+ {prompt.split()[-1] if prompt.split() else 'functionName'}();"""
220
+
221
+ # Default response
222
+ return f"""// Generated code for: {prompt}
223
+ // Language: {language}
224
+
225
+ // TODO: Implement your solution here
226
+ console.log("Code generated for: {prompt}");"""
227
+
228
+ def explain_code(self, code: str) -> str:
229
+ """Provide explanation for code"""
230
+ lines = code.split('\n')
231
+ explanation = "Code Analysis:\n\n"
232
+
233
+ # Simple pattern-based explanation
234
+ for i, line in enumerate(lines[:10], 1): # Limit to first 10 lines
235
+ line = line.strip()
236
+ if not line or line.startswith('//') or line.startswith('#'):
237
+ continue
238
+
239
+ if 'def ' in line:
240
+ explanation += f"Line {i}: Function definition - {line}\n"
241
+ elif 'function ' in line:
242
+ explanation += f"Line {i}: Function declaration - {line}\n"
243
+ elif 'import ' in line:
244
+ explanation += f"Line {i}: Import statement - {line}\n"
245
+ elif 'class ' in line:
246
+ explanation += f"Line {i}: Class definition - {line}\n"
247
+ elif '=' in line:
248
+ explanation += f"Line {i}: Variable assignment - {line}\n"
249
+ else:
250
+ explanation += f"Line {i}: Code statement - {line}\n"
251
+
252
+ return explanation + "\nThis is a basic analysis. For detailed explanations, consider adding more context."
253
+
254
+ def debug_code(self, code: str, error_message: str) -> str:
255
+ """Provide debugging suggestions"""
256
+ suggestions = [
257
+ "Check for syntax errors and typos",
258
+ "Verify all variables are properly declared",
259
+ "Ensure proper indentation",
260
+ "Check for missing imports or dependencies",
261
+ "Review logic flow and control structures"
262
+ ]
263
+
264
+ debug_help = f"Debugging Suggestions for Error: {error_message}\n\n"
265
+ debug_help += "\n".join(f"β€’ {suggestion}" for suggestion in suggestions)
266
+
267
+ # Add specific suggestions based on error patterns
268
+ if "syntax" in error_message.lower():
269
+ debug_help += "\n\nSyntax Error Specific:\nβ€’ Check for missing colons, brackets, or quotes\nβ€’ Verify proper indentation"
270
+ elif "undefined" in error_message.lower():
271
+ debug_help += "\n\nUndefined Error Specific:\nβ€’ Check variable scope\nβ€’ Ensure variables are declared before use"
272
+ elif "import" in error_message.lower():
273
+ debug_help += "\n\nImport Error Specific:\nβ€’ Verify module names are correct\nβ€’ Check if required packages are installed"
274
+
275
+ return debug_help
276
+
277
+ class CodeIDE:
278
+ """Main IDE application"""
279
+
280
+ def __init__(self):
281
+ self.executor = CodeExecutionEnvironment()
282
+ self.assistant = AICodeAssistant()
283
+ self.current_file = None
284
+ self.files = {}
285
+ self.chat_history = []
286
+
287
+ def create_new_file(self, filename: str, content: str = "") -> str:
288
+ """Create a new file"""
289
+ if not filename:
290
+ return "Error: Filename cannot be empty"
291
+
292
+ self.files[filename] = content
293
+ self.current_file = filename
294
+ return f"Created file: {filename}"
295
+
296
+ def save_file(self, filename: str, content: str) -> str:
297
+ """Save file content"""
298
+ self.files[filename] = content
299
+ return f"Saved: {filename}"
300
+
301
+ def load_file(self, filename: str) -> Tuple[str, str]:
302
+ """Load file content"""
303
+ if filename in self.files:
304
+ self.current_file = filename
305
+ return self.files[filename], f"Loaded: {filename}"
306
+ else:
307
+ return "", f"File not found: {filename}"
308
+
309
+ def delete_file(self, filename: str) -> str:
310
+ """Delete a file"""
311
+ if filename in self.files:
312
+ del self.files[filename]
313
+ if self.current_file == filename:
314
+ self.current_file = None
315
+ return f"Deleted: {filename}"
316
+ else:
317
+ return f"File not found: {filename}"
318
+
319
+ def get_file_list(self) -> List[str]:
320
+ """Get list of all files"""
321
+ return list(self.files.keys())
322
+
323
+ def generate_code_response(self, message: str, language: str, current_code: str = "") -> str:
324
+ """Generate AI response for code generation"""
325
+ response = self.assistant.generate_code(message, language, current_code)
326
+
327
+ # Add to chat history
328
+ self.chat_history.append({"role": "user", "content": message})
329
+ self.chat_history.append({"role": "assistant", "content": response})
330
+
331
+ return response
332
+
333
+ def explain_code_response(self, code: str) -> str:
334
+ """Explain code with AI"""
335
+ explanation = self.assistant.explain_code(code)
336
+
337
+ self.chat_history.append({"role": "user", "content": "Explain this code"})
338
+ self.chat_history.append({"role": "assistant", "content": explanation})
339
+
340
+ return explanation
341
+
342
+ def debug_code_response(self, code: str, error: str) -> str:
343
+ """Debug code with AI"""
344
+ debug_suggestion = self.assistant.debug_code(code, error)
345
+
346
+ self.chat_history.append({"role": "user", "content": f"Debug this error: {error}"})
347
+ self.chat_history.append({"role": "assistant", "content": debug_suggestion})
348
+
349
+ return debug_suggestion
350
+
351
+ def execute_current_code(self, code: str, language: str) -> Dict[str, Any]:
352
+ """Execute the current code"""
353
+ result = self.executor.execute_code(code, language)
354
+ return result
355
+
356
+ def get_chat_history(self) -> List[Dict[str, str]]:
357
+ """Get chat history"""
358
+ return self.chat_history
359
+
360
+ def clear_chat_history(self) -> str:
361
+ """Clear chat history"""
362
+ self.chat_history = []
363
+ return "Chat history cleared"
364
+
365
+ # Initialize IDE
366
+ ide = CodeIDE()
367
+
368
+ def create_interface():
369
+ """Create the Gradio interface"""
370
+
371
+ with gr.Blocks(
372
+ title="AnyCoder - AI Code Generation IDE",
373
+ theme=gr.themes.Soft(),
374
+ css="""
375
+ .header {
376
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
377
+ padding: 20px;
378
+ border-radius: 10px;
379
+ margin-bottom: 20px;
380
+ text-align: center;
381
+ }
382
+ .header h1 {
383
+ color: white;
384
+ margin: 0;
385
+ font-size: 2.5em;
386
+ }
387
+ .header p {
388
+ color: rgba(255,255,255,0.9);
389
+ margin: 10px 0 0 0;
390
+ font-size: 1.1em;
391
+ }
392
+ .header a {
393
+ color: white;
394
+ text-decoration: underline;
395
+ }
396
+ .code-editor {
397
+ font-family: 'Courier New', monospace;
398
+ font-size: 14px;
399
+ }
400
+ .chat-container {
401
+ height: 400px;
402
+ overflow-y: auto;
403
+ }
404
+ """
405
+ ) as demo:
406
+
407
+ with gr.Row():
408
+ gr.HTML("""
409
+ <div class="header">
410
+ <h1>πŸš€ AnyCoder</h1>
411
+ <p>Uncensored AI Code Generation IDE with Conversational Assistant</p>
412
+ <p>Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">anycoder</a></p>
413
+ </div>
414
+ """)
415
+
416
+ with gr.Tabs() as tabs:
417
+
418
+ # Code Editor Tab
419
+ with gr.TabItem("πŸ’» Code Editor", id="editor"):
420
+ with gr.Row():
421
+ with gr.Column(scale=1):
422
+ gr.Markdown("### πŸ“ File Manager")
423
+ file_list = gr.Dropdown(
424
+ choices=ide.get_file_list(),
425
+ label="Select File",
426
+ interactive=True
427
+ )
428
+ new_file_name = gr.Textbox(label="New File Name", placeholder="example.py")
429
+ with gr.Row():
430
+ create_btn = gr.Button("πŸ“„ New", variant="primary")
431
+ save_btn = gr.Button("πŸ’Ύ Save", variant="secondary")
432
+ delete_btn = gr.Button("πŸ—‘οΈ Delete", variant="stop")
433
+
434
+ gr.Markdown("### βš™οΈ Settings")
435
+ language_select = gr.Dropdown(
436
+ choices=["python", "javascript", "bash", "html", "css"],
437
+ value="python",
438
+ label="Language"
439
+ )
440
+ with gr.Row():
441
+ run_btn = gr.Button("▢️ Run Code", variant="primary")
442
+ clear_btn = gr.Button("🧹 Clear")
443
+
444
+ with gr.Column(scale=2):
445
+ gr.Markdown("### πŸ“ Code Editor")
446
+ code_editor = gr.Code(
447
+ label="Code",
448
+ language="python",
449
+ lines=20,
450
+ elem_classes=["code-editor"]
451
+ )
452
+
453
+ gr.Markdown("### πŸ“Š Output")
454
+ output_display = gr.Code(
455
+ label="Execution Output",
456
+ language="text",
457
+ lines=10,
458
+ interactive=False
459
+ )
460
+
461
+ # AI Assistant Tab
462
+ with gr.TabItem("πŸ€– AI Assistant", id="assistant"):
463
+ with gr.Row():
464
+ with gr.Column(scale=1):
465
+ gr.Markdown("### πŸ’¬ Chat with AI")
466
+ chatbot = gr.Chatbot(
467
+ type="messages",
468
+ elem_classes=["chat-container"],
469
+ height=400
470
+ )
471
+
472
+ with gr.Row():
473
+ msg_input = gr.Textbox(
474
+ label="Ask for code help...",
475
+ placeholder="Generate a React component for a todo list",
476
+ lines=2
477
+ )
478
+ send_btn = gr.Button("πŸ“€ Send", variant="primary")
479
+
480
+ with gr.Row():
481
+ clear_chat_btn = gr.Button("🧹 Clear Chat")
482
+ explain_btn = gr.Button("πŸ“– Explain Code")
483
+ debug_btn = gr.Button("πŸ› Debug Code")
484
+
485
+ with gr.Column(scale=1):
486
+ gr.Markdown("### 🎯 Quick Actions")
487
+ with gr.Accordion("Code Templates", open=True):
488
+ template_select = gr.Dropdown(
489
+ choices=["React Component", "FastAPI", "Gradio", "Express", "Python Function"],
490
+ label="Select Template",
491
+ value="React Component"
492
+ )
493
+ use_template_btn = gr.Button("πŸ“‹ Use Template", variant="secondary")
494
+
495
+ gr.Markdown("### πŸ› οΈ AI Tools")
496
+ ai_language = gr.Dropdown(
497
+ choices=["python", "javascript", "react", "html", "css"],
498
+ value="python",
499
+ label="Target Language"
500
+ )
501
+
502
+ gr.Markdown("### πŸ“š Recent History")
503
+ history_display = gr.JSON(
504
+ label="Chat History",
505
+ value=ide.get_chat_history()
506
+ )
507
+
508
+ # Project Files Tab
509
+ with gr.TabItem("πŸ“‚ Project Files", id="files"):
510
+ with gr.Row():
511
+ with gr.Column():
512
+ gr.Markdown("### πŸ“‹ All Files")
513
+ files_display = gr.DataFrame(
514
+ headers=["Filename", "Size", "Type"],
515
+ datatype=["str", "str", "str"],
516
+ interactive=False
517
+ )
518
+
519
+ refresh_files_btn = gr.Button("πŸ”„ Refresh Files", variant="primary")
520
+
521
+ gr.Markdown("### πŸ“€ Export Project")
522
+ export_format = gr.Dropdown(
523
+ choices=["ZIP", "JSON"],
524
+ value="ZIP",
525
+ label="Export Format"
526
+ )
527
+ export_btn = gr.Button("πŸ“¦ Export Project")
528
+
529
+ gr.Markdown("### πŸ“₯ Import Project")
530
+ import_file = gr.File(
531
+ label="Import Project File",
532
+ file_types=[".zip", ".json"]
533
+ )
534
+ import_btn = gr.Button("πŸ“₯ Import")
535
+
536
+ with gr.Column():
537
+ gr.Markdown("### πŸ“Š Project Statistics")
538
+ stats_display = gr.JSON(
539
+ label="Statistics",
540
+ value={}
541
+ )
542
+
543
+ gr.Markdown("### πŸ• Execution History")
544
+ exec_history = gr.DataFrame(
545
+ headers=["Time", "Language", "Status"],
546
+ datatype=["str", "str", "str"],
547
+ interactive=False
548
+ )
549
+
550
+ # Settings Tab
551
+ with gr.TabItem("βš™οΈ Settings", id="settings"):
552
+ with gr.Row():
553
+ with gr.Column():
554
+ gr.Markdown("### 🎨 Theme Settings")
555
+ theme_select = gr.Dropdown(
556
+ choices=["Soft", "Base", "Default", "Monochrome"],
557
+ value="Soft",
558
+ label="Theme"
559
+ )
560
+
561
+ gr.Markdown("### πŸ”§ Editor Settings")
562
+ font_size = gr.Slider(
563
+ minimum=10,
564
+ maximum=24,
565
+ value=14,
566
+ step=1,
567
+ label="Font Size"
568
+ )
569
+ tab_size = gr.Slider(
570
+ minimum=2,
571
+ maximum=8,
572
+ value=4,
573
+ step=1,
574
+ label="Tab Size"
575
+ )
576
+
577
+ gr.Markdown("### πŸ€– AI Settings")
578
+ ai_temperature = gr.Slider(
579
+ minimum=0.1,
580
+ maximum=1.0,
581
+ value=0.7,
582
+ step=0.1,
583
+ label="AI Creativity"
584
+ )
585
+ max_tokens = gr.Slider(
586
+ minimum=100,
587
+ maximum=2000,
588
+ value=1000,
589
+ step=100,
590
+ label="Max Response Length"
591
+ )
592
+
593
+ with gr.Column():
594
+ gr.Markdown("### πŸš€ Advanced Settings")
595
+ auto_save = gr.Checkbox(
596
+ label="Auto-save files",
597
+ value=True
598
+ )
599
+ line_numbers = gr.Checkbox(
600
+ label="Show line numbers",
601
+ value=True
602
+ )
603
+ word_wrap = gr.Checkbox(
604
+ label="Word wrap",
605
+ value=False
606
+ )
607
+
608
+ gr.Markdown("### πŸ”„ Reset Options")
609
+ with gr.Row():
610
+ reset_settings_btn = gr.Button("πŸ”„ Reset Settings", variant="secondary")
611
+ clear_all_btn = gr.Button("πŸ—‘οΈ Clear All Data", variant="stop")
612
+
613
+ # Event Handlers
614
+ def create_file(filename):
615
+ if filename:
616
+ result = ide.create_new_file(filename)
617
+ return result, gr.Dropdown(choices=ide.get_file_list(), value=filename)
618
+ return "Please enter a filename", gr.Dropdown()
619
+
620
+ def save_file(filename, content):
621
+ if filename:
622
+ return ide.save_file(filename, content)
623
+ return "No file selected"
624
+
625
+ def load_file(filename):
626
+ if filename:
627
+ content, message = ide.load_file(filename)
628
+ return content, message
629
+ return "", "No file selected"
630
+
631
+ def delete_file(filename):
632
+ if filename:
633
+ result = ide.delete_file(filename)
634
+ return result, gr.Dropdown(choices=ide.get_file_list())
635
+ return "No file selected", gr.Dropdown()
636
+
637
+ def run_code(code, language):
638
+ if code:
639
+ result = ide.execute_current_code(code, language)
640
+ output = result.get("output", "")
641
+ if result.get("error"):
642
+ output = f"ERROR:\n{output}\n\nSTDERR:\n{result.get('stderr', '')}"
643
+ return output
644
+ return "No code to run"
645
+
646
+ def chat_response(message, history, language, code):
647
+ if not message:
648
+ return "", history
649
+
650
+ # Generate AI response
651
+ response = ide.generate_code_response(message, language, code)
652
+ history.append({"role": "user", "content": message})
653
+ history.append({"role": "assistant", "content": response})
654
+
655
+ return "", history
656
+
657
+ def explain_current_code(code, history):
658
+ if code:
659
+ explanation = ide.explain_code_response(code)
660
+ history.append({"role": "user", "content": "Explain the current code"})
661
+ history.append({"role": "assistant", "content": explanation})
662
+ return history
663
+
664
+ def debug_current_code(code, history):
665
+ if code:
666
+ # Simulate finding an error
667
+ debug_response = ide.debug_code_response(code, "Example error message")
668
+ history.append({"role": "user", "content": "Debug the current code"})
669
+ history.append({"role": "assistant", "content": debug_response})
670
+ return history
671
+
672
+ def use_template(template, language):
673
+ template_map = {
674
+ "React Component": "react",
675
+ "FastAPI": "fastapi",
676
+ "Gradio": "gradio",
677
+ "Express": "express",
678
+ "Python Function": "python"
679
+ }
680
+ template_key = template_map.get(template, "python")
681
+ return ide.assistant.templates.get(template_key, "# Template not found")
682
+
683
+ def clear_chat():
684
+ ide.clear_chat_history()
685
+ return []
686
+
687
+ def refresh_files():
688
+ files = ide.get_file_list()
689
+ file_data = []
690
+ for file in files:
691
+ content = ide.files.get(file, "")
692
+ file_data.append([file, f"{len(content)} chars", file.split('.')[-1] if '.' in file else "text"])
693
+ return file_data
694
+
695
+ def update_stats():
696
+ files = ide.get_file_list()
697
+ total_chars = sum(len(ide.files.get(f, "")) for f in files)
698
+ return {
699
+ "total_files": len(files),
700
+ "total_characters": total_chars,
701
+ "languages": list(set(f.split('.')[-1] if '.' in f else "text" for f in files)),
702
+ "chat_messages": len(ide.chat_history)
703
+ }
704
+
705
+ def get_exec_history():
706
+ history = []
707
+ for record in ide.executor.history[-10:]: # Last 10 executions
708
+ status = "βœ… Success" if not record["result"].get("error") else "❌ Error"
709
+ history.append([record["timestamp"], record["language"], status])
710
+ return history
711
+
712
+ # Wire up events
713
+ create_btn.click(
714
+ create_file,
715
+ inputs=[new_file_name],
716
+ outputs=[gr.Textbox(label="Status"), file_list]
717
+ )
718
+
719
+ save_btn.click(
720
+ save_file,
721
+ inputs=[file_list, code_editor],
722
+ outputs=[gr.Textbox(label="Status")]
723
+ )
724
+
725
+ file_list.change(
726
+ load_file,
727
+ inputs=[file_list],
728
+ outputs=[code_editor, gr.Textbox(label="Status")]
729
+ )
730
+
731
+ delete_btn.click(
732
+ delete_file,
733
+ inputs=[file_list],
734
+ outputs=[gr.Textbox(label="Status"), file_list]
735
+ )
736
+
737
+ run_btn.click(
738
+ run_code,
739
+ inputs=[code_editor, language_select],
740
+ outputs=[output_display]
741
+ )
742
+
743
+ clear_btn.click(
744
+ lambda: ("", ""),
745
+ outputs=[code_editor, output_display]
746
+ )
747
+
748
+ send_btn.click(
749
+ chat_response,
750
+ inputs=[msg_input, chatbot, ai_language, code_editor],
751
+ outputs=[msg_input, chatbot]
752
+ )
753
+
754
+ msg_input.submit(
755
+ chat_response,
756
+ inputs=[msg_input, chatbot, ai_language, code_editor],
757
+ outputs=[msg_input, chatbot]
758
+ )
759
+
760
+ clear_chat_btn.click(
761
+ clear_chat,
762
+ outputs=[chatbot]
763
+ )
764
+
765
+ explain_btn.click(
766
+ explain_current_code,
767
+ inputs=[code_editor, chatbot],
768
+ outputs=[chatbot]
769
+ )
770
+
771
+ debug_btn.click(
772
+ debug_current_code,
773
+ inputs=[code_editor, chatbot],
774
+ outputs=[chatbot]
775
+ )
776
+
777
+ use_template_btn.click(
778
+ use_template,
779
+ inputs=[template_select, ai_language],
780
+ outputs=[code_editor]
781
+ )
782
+
783
+ refresh_files_btn.click(
784
+ refresh_files,
785
+ outputs=[files_display]
786
+ )
787
+
788
+ # Initialize displays
789
+ demo.load(
790
+ fn=lambda: (refresh_files(), update_stats(), get_exec_history()),
791
+ outputs=[files_display, stats_display, exec_history]
792
+ )
793
+
794
+ return demo
795
+
796
+ # Create and launch the application
797
+ if __name__ == "__main__":
798
+ demo = create_interface()
799
+ demo.launch(
800
+ server_name="0.0.0.0",
801
+ server_port=7860,
802
+ share=True,
803
+ show_error=True,
804
+ show_api=True
805
+ )
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio>=4.0.0