-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
198 lines (166 loc) · 6.46 KB
/
app.py
File metadata and controls
198 lines (166 loc) · 6.46 KB
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
from flask import Flask, request, render_template, jsonify
import subprocess
import sys
import tempfile
import os
import requests
import pkg_resources
import threading
import time
from datetime import datetime
app = Flask(__name__)
GEMINI_API_KEY = 'AIzaSyA3SlVaUvDgS6FW7DUdVHuFduByaIOeDmM'
GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent'
RENDER_URL = 'https://python-web-25i2.onrender.com/'
def ping_render():
while True:
try:
response = requests.get(RENDER_URL)
if response.status_code == 200:
print(f"[{datetime.now()}] Ping successful - Status: {response.status_code}")
else:
print(f"[{datetime.now()}] Ping failed - Status: {response.status_code}")
except Exception as e:
print(f"[{datetime.now()}] Ping error: {str(e)}")
time.sleep(30) # Wait for 30 seconds
# Start the ping thread
ping_thread = threading.Thread(target=ping_render, daemon=True)
ping_thread.start()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/execute', methods=['POST'])
def execute_code():
code = request.json.get('code')
if not code:
return jsonify({'error': 'No code provided'}), 400
try:
# Create a temporary file to store the code
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
f.write(code)
temp_file_name = f.name
# Execute the code in a subprocess with timeout
result = subprocess.run([sys.executable, temp_file_name],
capture_output=True,
text=True,
timeout=30)
# Clean up the temporary file
os.unlink(temp_file_name)
return jsonify({
'output': result.stdout,
'error': result.stderr,
'returncode': result.returncode
})
except subprocess.TimeoutExpired:
return jsonify({'error': 'Execution timed out (30 seconds limit)'}), 408
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/get_fix', methods=['POST'])
def get_fix():
code = request.json.get('code')
error = request.json.get('error')
if not code or not error:
return jsonify({'error': 'Code and error message are required'}), 400
try:
prompt = f"""As a Python expert, analyze this code and error message, then provide:\n1. A brief explanation of the error\n2. The corrected code\n\nCode:\n{code}\n\nError:\n{error}\n\nPlease format your response as:\nEXPLANATION:\n[Your explanation here]\n\nFIXED_CODE:\n[Your corrected code here]"""
headers = {
'Content-Type': 'application/json',
}
data = {
'contents': [{
'parts': [{
'text': prompt
}]
}]
}
response = requests.post(
f'{GEMINI_API_URL}?key={GEMINI_API_KEY}',
headers=headers,
json=data
)
if response.status_code != 200:
return jsonify({'error': f'API request failed: {response.text}'}), 500
response_data = response.json()
response_text = response_data['candidates'][0]['content']['parts'][0]['text']
# Parse the response to separate explanation and fixed code
parts = response_text.split('FIXED_CODE:')
explanation = parts[0].replace('EXPLANATION:', '').strip()
fixed_code = parts[1].strip() if len(parts) > 1 else ''
return jsonify({
'explanation': explanation,
'fixed_code': fixed_code
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/ai_chat', methods=['POST'])
def ai_chat():
user_message = request.json.get('message')
if not user_message:
return jsonify({'error': 'No message provided'}), 400
try:
headers = {
'Content-Type': 'application/json',
}
data = {
'contents': [{
'parts': [{
'text': user_message
}]
}]
}
response = requests.post(
f'{GEMINI_API_URL}?key={GEMINI_API_KEY}',
headers=headers,
json=data
)
if response.status_code != 200:
return jsonify({'error': f'API request failed: {response.text}'}), 500
response_data = response.json()
ai_reply = response_data['candidates'][0]['content']['parts'][0]['text']
return jsonify({'reply': ai_reply})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/install_package', methods=['POST'])
def install_package():
package = request.json.get('package')
if not package:
return jsonify({'error': 'No package name provided'}), 400
try:
# Install the package using pip
result = subprocess.run(
[sys.executable, '-m', 'pip', 'install', package],
capture_output=True,
text=True
)
if result.returncode != 0:
return jsonify({'error': result.stderr}), 500
return jsonify({'message': f'Successfully installed {package}'})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/uninstall_package', methods=['POST'])
def uninstall_package():
package = request.json.get('package')
if not package:
return jsonify({'error': 'No package name provided'}), 400
try:
# Uninstall the package using pip
result = subprocess.run(
[sys.executable, '-m', 'pip', 'uninstall', '-y', package],
capture_output=True,
text=True
)
if result.returncode != 0:
return jsonify({'error': result.stderr}), 500
return jsonify({'message': f'Successfully uninstalled {package}'})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/list_packages', methods=['GET'])
def list_packages():
try:
# Get list of installed packages
installed_packages = [pkg.key for pkg in pkg_resources.working_set]
return jsonify({'packages': installed_packages})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)))