File size: 6,078 Bytes
5afdcff b878efb 5afdcff 0c72e04 ef280d5 5afdcff b878efb 5afdcff ef280d5 b878efb 5afdcff 0c72e04 b878efb 5afdcff b878efb 5afdcff b878efb 0c72e04 b878efb 945956c b878efb 5afdcff b878efb 5afdcff 0c72e04 945956c b878efb 5afdcff b878efb 5afdcff b878efb 945956c 0c72e04 945956c 0c72e04 945956c 0c72e04 945956c 0c72e04 945956c 0c72e04 945956c 0c72e04 5afdcff 0c72e04 945956c ef280d5 5afdcff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
from flask import Flask, request, jsonify, render_template, send_from_directory
import os
import subprocess
import tempfile
import shutil
import sys
import google.generativeai as genai
import re
app = Flask(__name__)
# Create a temporary directory for operations
temp_dir = tempfile.mkdtemp()
current_dir = temp_dir
# Configure Gemini AI
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
generation_config = {
"temperature": 0.7,
"top_p": 1,
"top_k": 40,
"max_output_tokens": 1024,
}
model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config=generation_config,
)
system_instruction = """
You are a code generation assistant. Follow these strict rules:
1. Respond ONLY with code in ```python or ```bash blocks
2. Never include explanations or comments
3. For file operations, create complete executable scripts
4. Handle errors within the code itself
5. Format example:
User: Create a file that prints hello
Response: ```python\nprint("hello")\n```
"""
chat = model.start_chat(history=[])
def execute_command(command, cwd=None):
"""Executes a command and returns the output."""
process = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=cwd or current_dir
)
stdout, stderr = process.communicate()
return stdout + stderr
def extract_code(response):
"""Extracts clean code from Gemini response"""
code_blocks = re.findall(r'```(?:python|bash)\n(.*?)\n```', response, re.DOTALL)
return code_blocks[0].strip() if code_blocks else None
@app.route("/")
def index():
return render_template("index.html")
@app.route("/execute", methods=["POST"])
def execute_code():
global current_dir
command = request.json.get("code", "").strip()
if not command:
return jsonify({"result": "Error: No command provided."})
try:
if command.lower().startswith("ai:"):
ai_command = command[3:].strip()
response = chat.send_message(f"{system_instruction}\nUser request: {ai_command}")
code = extract_code(response.text)
if not code:
return jsonify({"result": "Error: No valid code generated", "type": "error"})
# Handle Python code
if "print(" in code or "def " in code or "import " in code:
filename = "generated_script.py"
filepath = os.path.join(current_dir, filename)
with open(filepath, 'w') as f:
f.write(code)
return jsonify({
"result": f"File created: {filename}",
"type": "code",
"file": filename,
"content": code
})
# Handle bash commands
elif any(cmd in code for cmd in ["pip", "git", "cd", "mkdir"]):
result = execute_command(code)
return jsonify({
"result": f"Command executed:\n{result}",
"type": "command"
})
return jsonify({"result": "Unsupported code type", "type": "error"})
elif command == "show files":
files = os.listdir(current_dir)
return jsonify({"result": "Files:\n" + "\n".join(files), "type": "files"})
elif command.startswith("cd "):
new_dir = os.path.join(current_dir, command[3:])
if os.path.isdir(new_dir):
current_dir = os.path.abspath(new_dir)
return jsonify({"result": f"Changed directory to: {current_dir}", "type": "directory"})
return jsonify({"result": f"Error: Directory not found: {new_dir}", "type": "error"})
elif command.startswith("!"):
result = execute_command(command[1:])
return jsonify({"result": result, "type": "command"})
elif command.startswith("pip install"):
result = execute_command(f"{sys.executable} -m {command}")
return jsonify({"result": result, "type": "package"})
elif command.endswith(".py"):
result = execute_command(f"{sys.executable} {command}")
return jsonify({"result": result, "type": "script"})
else:
return jsonify({"result": "Unrecognized command", "type": "error"})
except Exception as e:
return jsonify({"result": f"Error: {str(e)}", "type": "error"})
@app.route("/save_file", methods=["POST"])
def save_file():
try:
filename = request.json.get("filename")
content = request.json.get("content")
filepath = os.path.join(current_dir, filename)
with open(filepath, 'w') as f:
f.write(content)
return jsonify({"result": f"File {filename} saved", "type": "file"})
except Exception as e:
return jsonify({"result": f"Save error: {str(e)}", "type": "error"})
@app.route("/cleanup", methods=["POST"])
def cleanup():
global temp_dir, current_dir
try:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
temp_dir = tempfile.mkdtemp()
current_dir = temp_dir
return jsonify({"result": "Environment reset", "type": "system"})
except Exception as e:
return jsonify({"result": f"Cleanup error: {str(e)}", "type": "error"})
@app.route("/list_files", methods=["GET"])
def list_files():
try:
files = os.listdir(current_dir)
return jsonify({"files": files, "type": "files"})
except Exception as e:
return jsonify({"result": f"List error: {str(e)}", "type": "error"})
@app.route("/download/<path:filename>", methods=["GET"])
def download_file(filename):
try:
return send_from_directory(current_dir, filename, as_attachment=True)
except Exception as e:
return jsonify({"result": f"Download error: {str(e)}", "type": "error"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860) |