File size: 8,159 Bytes
a15e38b 5bc4351 2c91ea0 382764a a15e38b a2ea954 21fe3fa 2c91ea0 a15e38b a2ea954 7c29fe7 a2ea954 7c29fe7 a2ea954 a15e38b 4d30d4b a15e38b 1917e67 a15e38b 2c91ea0 a2ea954 7c29fe7 a2ea954 2a6bd1c a15e38b a794cee a15e38b 2a6bd1c a15e38b a2ea954 |
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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
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
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.9,
"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 an AI-powered terminal assistant. Your role is to interpret user requests and execute appropriate terminal commands. Follow these guidelines:
1. Understand and execute various commands, including but not limited to:
- pip install: For installing Python packages
- git clone: For cloning repositories
- cd: For changing directories
- Python script execution: For running .py files
- show files: List files in the current directory
- hide files: Hide the file explorer
- new file: Create a new file
- edit file: Open a file for editing
2. Provide the exact command to be executed, without any explanation or additional text.
3. For pip install requests, always prefix the command with '!python -m' to ensure proper execution.
4. For git clone requests, provide the full 'git clone' command with the repository URL.
5. For cd requests, simply provide the 'cd' command with the specified directory.
6. For Python script execution, provide the command to run the script (e.g., '!python script_name.py').
7. For show files, respond with 'show files'.
8. For hide files, respond with 'hide files'.
9. For new file requests, respond with 'new file filename.ext', where filename.ext is the name provided by the user or a default name if not specified.
10. For edit file requests, respond with 'edit filename.ext', where filename.ext is the name of the file to be edited.
11. If a request is unclear or doesn't match any known command type, respond with "Unclear request. Please provide more details."
Always respond with ONLY the command to be executed, nothing else.
"""
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
@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:"):
# Process command with Gemini AI
ai_command = command[3:].strip()
response = chat.send_message(system_instruction + f"\nUser request: {ai_command}")
ai_result = response.text.strip()
# Execute the AI-suggested command
if ai_result.startswith("!python -m pip install"):
result = execute_command(ai_result[1:]) # Remove the leading '!'
elif ai_result.startswith("git clone"):
result = execute_command(ai_result)
elif ai_result.startswith("cd "):
new_dir = os.path.join(current_dir, ai_result[3:])
if os.path.isdir(new_dir):
current_dir = os.path.abspath(new_dir)
result = f"Changed directory to: {current_dir}"
else:
result = f"Error: Directory not found: {new_dir}"
elif ai_result.startswith("!python "):
result = execute_command(ai_result[1:]) # Remove the leading '!'
elif ai_result == "show files":
files = os.listdir(current_dir)
result = "Files in current directory:\n" + "\n".join(files)
elif ai_result == "hide files":
result = "Files hidden."
elif ai_result.startswith("new file "):
filename = ai_result[9:].strip()
filepath = os.path.join(current_dir, filename)
with open(filepath, 'w') as f:
pass # Create an empty file
result = f"Created new file: {filename}"
elif ai_result.startswith("edit "):
filename = ai_result[5:].strip()
filepath = os.path.join(current_dir, filename)
if os.path.exists(filepath):
result = "Enter code:"
return jsonify({"result": result, "action": "edit", "filename": filename})
else:
result = f"Error: File {filename} not found."
else:
result = f"Unclear AI response: {ai_result}"
return jsonify({"result": f"AI Executed: {ai_result}\n\nOutput:\n{result}"})
elif command == "show files":
files = os.listdir(current_dir)
return jsonify({"result": "Files in current directory:\n" + "\n".join(files)})
elif command == "hide files":
return jsonify({"result": "Files hidden."})
elif command.startswith("new file "):
filename = command[9:].strip()
filepath = os.path.join(current_dir, filename)
with open(filepath, 'w') as f:
pass # Create an empty file
return jsonify({"result": f"Created new file: {filename}"})
elif command.startswith("edit "):
filename = command[5:].strip()
filepath = os.path.join(current_dir, filename)
if os.path.exists(filepath):
return jsonify({"result": "Enter code:", "action": "edit", "filename": filename})
else:
return jsonify({"result": f"Error: File {filename} not found."})
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}"})
else:
return jsonify({"result": f"Error: Directory not found: {new_dir}"})
elif command.startswith("!"):
result = execute_command(command[1:])
elif command.startswith("pip install"):
result = execute_command(f"{sys.executable} -m {command}")
elif command.startswith("git "):
result = execute_command(command)
else:
if command.endswith(".py"):
result = execute_command(f"{sys.executable} {command}")
else:
result = execute_command(f"{sys.executable} -c \"{command}\"")
return jsonify({"result": result})
except Exception as e:
return jsonify({"result": f"Error: {str(e)}"})
@app.route("/save_file", methods=["POST"])
def save_file():
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 successfully."})
@app.route("/cleanup", methods=["POST"])
def cleanup():
global temp_dir, current_dir
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
temp_dir = tempfile.mkdtemp()
current_dir = temp_dir
return jsonify({"result": "Temporary files cleaned up."})
@app.route("/list_files", methods=["GET"])
def list_files():
files = os.listdir(current_dir)
return jsonify({"files": files})
@app.route("/download/<path:filename>", methods=["GET"])
def download_file(filename):
return send_from_directory(current_dir, filename, as_attachment=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)
|