import gradio as gr
import json
import os
import re
import time
import uuid
from datetime import datetime
from typing import Dict, List, Tuple, Any, Optional
import subprocess
import tempfile
import shutil
class CodeExecutionEnvironment:
"""Safe code execution environment with sandboxing"""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
self.history = []
def execute_code(self, code: str, language: str = "python") -> Dict[str, Any]:
"""Execute code in a sandboxed environment"""
execution_id = str(uuid.uuid4())[:8]
timestamp = datetime.now().isoformat()
try:
if language.lower() == "python":
result = self._execute_python(code)
elif language.lower() == "javascript":
result = self._execute_javascript(code)
elif language.lower() == "bash":
result = self._execute_bash(code)
else:
result = {"output": f"Language {language} not supported", "error": True}
execution_record = {
"id": execution_id,
"timestamp": timestamp,
"code": code,
"language": language,
"result": result
}
self.history.append(execution_record)
return result
except Exception as e:
return {
"output": f"Execution error: {str(e)}",
"error": True,
"execution_id": execution_id
}
def _execute_python(self, code: str) -> Dict[str, Any]:
"""Execute Python code safely"""
try:
# Create a temporary file
temp_file = os.path.join(self.temp_dir, f"temp_{uuid.uuid4()}.py")
with open(temp_file, 'w') as f:
f.write(code)
# Execute with timeout
result = subprocess.run(
['python', temp_file],
capture_output=True,
text=True,
timeout=30,
cwd=self.temp_dir
)
return {
"output": result.stdout,
"error": result.returncode != 0,
"stderr": result.stderr if result.stderr else None
}
except subprocess.TimeoutExpired:
return {"output": "Code execution timed out (30s limit)", "error": True}
except Exception as e:
return {"output": f"Python execution error: {str(e)}", "error": True}
def _execute_javascript(self, code: str) -> Dict[str, Any]:
"""Execute JavaScript code using Node.js"""
try:
temp_file = os.path.join(self.temp_dir, f"temp_{uuid.uuid4()}.js")
with open(temp_file, 'w') as f:
f.write(code)
result = subprocess.run(
['node', temp_file],
capture_output=True,
text=True,
timeout=30,
cwd=self.temp_dir
)
return {
"output": result.stdout,
"error": result.returncode != 0,
"stderr": result.stderr if result.stderr else None
}
except subprocess.TimeoutExpired:
return {"output": "Code execution timed out (30s limit)", "error": True}
except FileNotFoundError:
return {"output": "Node.js not found. Please install Node.js to run JavaScript.", "error": True}
except Exception as e:
return {"output": f"JavaScript execution error: {str(e)}", "error": True}
def _execute_bash(self, code: str) -> Dict[str, Any]:
"""Execute bash commands"""
try:
result = subprocess.run(
code,
shell=True,
capture_output=True,
text=True,
timeout=30,
cwd=self.temp_dir
)
return {
"output": result.stdout,
"error": result.returncode != 0,
"stderr": result.stderr if result.stderr else None
}
except subprocess.TimeoutExpired:
return {"output": "Command execution timed out (30s limit)", "error": True}
except Exception as e:
return {"output": f"Bash execution error: {str(e)}", "error": True}
def cleanup(self):
"""Clean up temporary files"""
try:
shutil.rmtree(self.temp_dir)
except:
pass
class AICodeAssistant:
"""AI-powered code generation and assistance"""
def __init__(self):
self.templates = {
"react": """import React from 'react';
function Component() {{
return (
Hello World
);
}}
export default Component;""",
"python": """def main():
print("Hello, World!")
if __name__ == "__main__":
main()""",
"fastapi": """from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {{"message": "Hello World"}}""",
"gradio": """import gradio as gr
def greet(name):
return f"Hello {name}!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()""",
"express": """const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.json({ message: 'Hello World!' });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});""",
}
def generate_code(self, prompt: str, language: str, context: str = "") -> str:
"""Generate code based on prompt and language"""
# Enhanced code generation with context awareness
language = language.lower()
# Check for template usage
if any(template in prompt.lower() for template in ["react", "component", "jsx"]):
return self.templates["react"]
elif "fastapi" in prompt.lower():
return self.templates["fastapi"]
elif "gradio" in prompt.lower():
return self.templates["gradio"]
elif "express" in prompt.lower():
return self.templates["express"]
elif "python" in prompt.lower() or language == "python":
return self.templates["python"]
# Generate code based on common patterns
if "function" in prompt.lower() or "def" in prompt.lower():
if language == "python":
return f"""def {prompt.split()[-1] if prompt.split() else 'function_name'}():
# TODO: Implement function
pass
# Example usage
if __name__ == "__main__":
result = {prompt.split()[-1] if prompt.split() else 'function_name'}()
print(result)"""
elif language in ["javascript", "js"]:
return f"""function {prompt.split()[-1] if prompt.split() else 'functionName'}() {{
// TODO: Implement function
console.log("Function called");
}}
// Example usage
{prompt.split()[-1] if prompt.split() else 'functionName'}();"""
# Default response
return f"""// Generated code for: {prompt}
// Language: {language}
// TODO: Implement your solution here
console.log("Code generated for: {prompt}");"""
def explain_code(self, code: str) -> str:
"""Provide explanation for code"""
lines = code.split('\n')
explanation = "Code Analysis:\n\n"
# Simple pattern-based explanation
for i, line in enumerate(lines[:10], 1): # Limit to first 10 lines
line = line.strip()
if not line or line.startswith('//') or line.startswith('#'):
continue
if 'def ' in line:
explanation += f"Line {i}: Function definition - {line}\n"
elif 'function ' in line:
explanation += f"Line {i}: Function declaration - {line}\n"
elif 'import ' in line:
explanation += f"Line {i}: Import statement - {line}\n"
elif 'class ' in line:
explanation += f"Line {i}: Class definition - {line}\n"
elif '=' in line:
explanation += f"Line {i}: Variable assignment - {line}\n"
else:
explanation += f"Line {i}: Code statement - {line}\n"
return explanation + "\nThis is a basic analysis. For detailed explanations, consider adding more context."
def debug_code(self, code: str, error_message: str) -> str:
"""Provide debugging suggestions"""
suggestions = [
"Check for syntax errors and typos",
"Verify all variables are properly declared",
"Ensure proper indentation",
"Check for missing imports or dependencies",
"Review logic flow and control structures"
]
debug_help = f"Debugging Suggestions for Error: {error_message}\n\n"
debug_help += "\n".join(f"• {suggestion}" for suggestion in suggestions)
# Add specific suggestions based on error patterns
if "syntax" in error_message.lower():
debug_help += "\n\nSyntax Error Specific:\n• Check for missing colons, brackets, or quotes\n• Verify proper indentation"
elif "undefined" in error_message.lower():
debug_help += "\n\nUndefined Error Specific:\n• Check variable scope\n• Ensure variables are declared before use"
elif "import" in error_message.lower():
debug_help += "\n\nImport Error Specific:\n• Verify module names are correct\n• Check if required packages are installed"
return debug_help
class CodeIDE:
"""Main IDE application"""
def __init__(self):
self.executor = CodeExecutionEnvironment()
self.assistant = AICodeAssistant()
self.current_file = None
self.files = {}
self.chat_history = []
def create_new_file(self, filename: str, content: str = "") -> str:
"""Create a new file"""
if not filename:
return "Error: Filename cannot be empty"
self.files[filename] = content
self.current_file = filename
return f"Created file: {filename}"
def save_file(self, filename: str, content: str) -> str:
"""Save file content"""
self.files[filename] = content
return f"Saved: {filename}"
def load_file(self, filename: str) -> Tuple[str, str]:
"""Load file content"""
if filename in self.files:
self.current_file = filename
return self.files[filename], f"Loaded: {filename}"
else:
return "", f"File not found: {filename}"
def delete_file(self, filename: str) -> str:
"""Delete a file"""
if filename in self.files:
del self.files[filename]
if self.current_file == filename:
self.current_file = None
return f"Deleted: {filename}"
else:
return f"File not found: {filename}"
def get_file_list(self) -> List[str]:
"""Get list of all files"""
return list(self.files.keys())
def generate_code_response(self, message: str, language: str, current_code: str = "") -> str:
"""Generate AI response for code generation"""
response = self.assistant.generate_code(message, language, current_code)
# Add to chat history
self.chat_history.append({"role": "user", "content": message})
self.chat_history.append({"role": "assistant", "content": response})
return response
def explain_code_response(self, code: str) -> str:
"""Explain code with AI"""
explanation = self.assistant.explain_code(code)
self.chat_history.append({"role": "user", "content": "Explain this code"})
self.chat_history.append({"role": "assistant", "content": explanation})
return explanation
def debug_code_response(self, code: str, error: str) -> str:
"""Debug code with AI"""
debug_suggestion = self.assistant.debug_code(code, error)
self.chat_history.append({"role": "user", "content": f"Debug this error: {error}"})
self.chat_history.append({"role": "assistant", "content": debug_suggestion})
return debug_suggestion
def execute_current_code(self, code: str, language: str) -> Dict[str, Any]:
"""Execute the current code"""
result = self.executor.execute_code(code, language)
return result
def get_chat_history(self) -> List[Dict[str, str]]:
"""Get chat history"""
return self.chat_history
def clear_chat_history(self) -> str:
"""Clear chat history"""
self.chat_history = []
return "Chat history cleared"
# Initialize IDE
ide = CodeIDE()
def create_interface():
"""Create the Gradio interface"""
with gr.Blocks(
title="AnyCoder - AI Code Generation IDE",
theme=gr.themes.Soft(),
css="""
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
text-align: center;
}
.header h1 {
color: white;
margin: 0;
font-size: 2.5em;
}
.header p {
color: rgba(255,255,255,0.9);
margin: 10px 0 0 0;
font-size: 1.1em;
}
.header a {
color: white;
text-decoration: underline;
}
.code-editor {
font-family: 'Courier New', monospace;
font-size: 14px;
}
.chat-container {
height: 400px;
overflow-y: auto;
}
"""
) as demo:
with gr.Row():
gr.HTML("""
""")
with gr.Tabs() as tabs:
# Code Editor Tab
with gr.TabItem("💻 Code Editor", id="editor"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 📁 File Manager")
file_list = gr.Dropdown(
choices=ide.get_file_list(),
label="Select File",
interactive=True
)
new_file_name = gr.Textbox(label="New File Name", placeholder="example.py")
with gr.Row():
create_btn = gr.Button("📄 New", variant="primary")
save_btn = gr.Button("💾 Save", variant="secondary")
delete_btn = gr.Button("🗑️ Delete", variant="stop")
gr.Markdown("### ⚙️ Settings")
language_select = gr.Dropdown(
choices=["python", "javascript", "bash", "html", "css"],
value="python",
label="Language"
)
with gr.Row():
run_btn = gr.Button("▶️ Run Code", variant="primary")
clear_btn = gr.Button("🧹 Clear")
with gr.Column(scale=2):
gr.Markdown("### 📝 Code Editor")
code_editor = gr.Code(
label="Code",
language="python",
lines=20,
elem_classes=["code-editor"]
)
gr.Markdown("### 📊 Output")
output_display = gr.Code(
label="Execution Output",
language="text",
lines=10,
interactive=False
)
# AI Assistant Tab
with gr.TabItem("🤖 AI Assistant", id="assistant"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 💬 Chat with AI")
chatbot = gr.Chatbot(
type="messages",
elem_classes=["chat-container"],
height=400
)
with gr.Row():
msg_input = gr.Textbox(
label="Ask for code help...",
placeholder="Generate a React component for a todo list",
lines=2
)
send_btn = gr.Button("📤 Send", variant="primary")
with gr.Row():
clear_chat_btn = gr.Button("🧹 Clear Chat")
explain_btn = gr.Button("📖 Explain Code")
debug_btn = gr.Button("🐛 Debug Code")
with gr.Column(scale=1):
gr.Markdown("### 🎯 Quick Actions")
with gr.Accordion("Code Templates", open=True):
template_select = gr.Dropdown(
choices=["React Component", "FastAPI", "Gradio", "Express", "Python Function"],
label="Select Template",
value="React Component"
)
use_template_btn = gr.Button("📋 Use Template", variant="secondary")
gr.Markdown("### 🛠️ AI Tools")
ai_language = gr.Dropdown(
choices=["python", "javascript", "react", "html", "css"],
value="python",
label="Target Language"
)
gr.Markdown("### 📚 Recent History")
history_display = gr.JSON(
label="Chat History",
value=ide.get_chat_history()
)
# Project Files Tab
with gr.TabItem("📂 Project Files", id="files"):
with gr.Row():
with gr.Column():
gr.Markdown("### 📋 All Files")
files_display = gr.DataFrame(
headers=["Filename", "Size", "Type"],
datatype=["str", "str", "str"],
interactive=False
)
refresh_files_btn = gr.Button("🔄 Refresh Files", variant="primary")
gr.Markdown("### 📤 Export Project")
export_format = gr.Dropdown(
choices=["ZIP", "JSON"],
value="ZIP",
label="Export Format"
)
export_btn = gr.Button("📦 Export Project")
gr.Markdown("### 📥 Import Project")
import_file = gr.File(
label="Import Project File",
file_types=[".zip", ".json"]
)
import_btn = gr.Button("📥 Import")
with gr.Column():
gr.Markdown("### 📊 Project Statistics")
stats_display = gr.JSON(
label="Statistics",
value={}
)
gr.Markdown("### 🕐 Execution History")
exec_history = gr.DataFrame(
headers=["Time", "Language", "Status"],
datatype=["str", "str", "str"],
interactive=False
)
# Settings Tab
with gr.TabItem("⚙️ Settings", id="settings"):
with gr.Row():
with gr.Column():
gr.Markdown("### 🎨 Theme Settings")
theme_select = gr.Dropdown(
choices=["Soft", "Base", "Default", "Monochrome"],
value="Soft",
label="Theme"
)
gr.Markdown("### 🔧 Editor Settings")
font_size = gr.Slider(
minimum=10,
maximum=24,
value=14,
step=1,
label="Font Size"
)
tab_size = gr.Slider(
minimum=2,
maximum=8,
value=4,
step=1,
label="Tab Size"
)
gr.Markdown("### 🤖 AI Settings")
ai_temperature = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.7,
step=0.1,
label="AI Creativity"
)
max_tokens = gr.Slider(
minimum=100,
maximum=2000,
value=1000,
step=100,
label="Max Response Length"
)
with gr.Column():
gr.Markdown("### 🚀 Advanced Settings")
auto_save = gr.Checkbox(
label="Auto-save files",
value=True
)
line_numbers = gr.Checkbox(
label="Show line numbers",
value=True
)
word_wrap = gr.Checkbox(
label="Word wrap",
value=False
)
gr.Markdown("### 🔄 Reset Options")
with gr.Row():
reset_settings_btn = gr.Button("🔄 Reset Settings", variant="secondary")
clear_all_btn = gr.Button("🗑️ Clear All Data", variant="stop")
# Event Handlers
def create_file(filename):
if filename:
result = ide.create_new_file(filename)
return result, gr.Dropdown(choices=ide.get_file_list(), value=filename)
return "Please enter a filename", gr.Dropdown()
def save_file(filename, content):
if filename:
return ide.save_file(filename, content)
return "No file selected"
def load_file(filename):
if filename:
content, message = ide.load_file(filename)
return content, message
return "", "No file selected"
def delete_file(filename):
if filename:
result = ide.delete_file(filename)
return result, gr.Dropdown(choices=ide.get_file_list())
return "No file selected", gr.Dropdown()
def run_code(code, language):
if code:
result = ide.execute_current_code(code, language)
output = result.get("output", "")
if result.get("error"):
output = f"ERROR:\n{output}\n\nSTDERR:\n{result.get('stderr', '')}"
return output
return "No code to run"
def chat_response(message, history, language, code):
if not message:
return "", history
# Generate AI response
response = ide.generate_code_response(message, language, code)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": response})
return "", history
def explain_current_code(code, history):
if code:
explanation = ide.explain_code_response(code)
history.append({"role": "user", "content": "Explain the current code"})
history.append({"role": "assistant", "content": explanation})
return history
def debug_current_code(code, history):
if code:
# Simulate finding an error
debug_response = ide.debug_code_response(code, "Example error message")
history.append({"role": "user", "content": "Debug the current code"})
history.append({"role": "assistant", "content": debug_response})
return history
def use_template(template, language):
template_map = {
"React Component": "react",
"FastAPI": "fastapi",
"Gradio": "gradio",
"Express": "express",
"Python Function": "python"
}
template_key = template_map.get(template, "python")
return ide.assistant.templates.get(template_key, "# Template not found")
def clear_chat():
ide.clear_chat_history()
return []
def refresh_files():
files = ide.get_file_list()
file_data = []
for file in files:
content = ide.files.get(file, "")
file_data.append([file, f"{len(content)} chars", file.split('.')[-1] if '.' in file else "text"])
return file_data
def update_stats():
files = ide.get_file_list()
total_chars = sum(len(ide.files.get(f, "")) for f in files)
return {
"total_files": len(files),
"total_characters": total_chars,
"languages": list(set(f.split('.')[-1] if '.' in f else "text" for f in files)),
"chat_messages": len(ide.chat_history)
}
def get_exec_history():
history = []
for record in ide.executor.history[-10:]: # Last 10 executions
status = "✅ Success" if not record["result"].get("error") else "❌ Error"
history.append([record["timestamp"], record["language"], status])
return history
# Wire up events
create_btn.click(
create_file,
inputs=[new_file_name],
outputs=[gr.Textbox(label="Status"), file_list]
)
save_btn.click(
save_file,
inputs=[file_list, code_editor],
outputs=[gr.Textbox(label="Status")]
)
file_list.change(
load_file,
inputs=[file_list],
outputs=[code_editor, gr.Textbox(label="Status")]
)
delete_btn.click(
delete_file,
inputs=[file_list],
outputs=[gr.Textbox(label="Status"), file_list]
)
run_btn.click(
run_code,
inputs=[code_editor, language_select],
outputs=[output_display]
)
clear_btn.click(
lambda: ("", ""),
outputs=[code_editor, output_display]
)
send_btn.click(
chat_response,
inputs=[msg_input, chatbot, ai_language, code_editor],
outputs=[msg_input, chatbot]
)
msg_input.submit(
chat_response,
inputs=[msg_input, chatbot, ai_language, code_editor],
outputs=[msg_input, chatbot]
)
clear_chat_btn.click(
clear_chat,
outputs=[chatbot]
)
explain_btn.click(
explain_current_code,
inputs=[code_editor, chatbot],
outputs=[chatbot]
)
debug_btn.click(
debug_current_code,
inputs=[code_editor, chatbot],
outputs=[chatbot]
)
use_template_btn.click(
use_template,
inputs=[template_select, ai_language],
outputs=[code_editor]
)
refresh_files_btn.click(
refresh_files,
outputs=[files_display]
)
# Initialize displays
demo.load(
fn=lambda: (refresh_files(), update_stats(), get_exec_history()),
outputs=[files_display, stats_display, exec_history]
)
return demo
# Create and launch the application
if __name__ == "__main__":
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
show_error=True,
show_api=True
)