-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
475 lines (368 loc) · 14.2 KB
/
server.py
File metadata and controls
475 lines (368 loc) · 14.2 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
from flask import Flask, request, jsonify, render_template
import json
import os
import tempfile
import requests
import subprocess
import re
import hashlib
from google import genai
app = Flask(__name__)
CONFIG_PATH = "gemini_config.json"
CACHE_FILE = 'leetcode_cache.json'
safe_code_hashes = set()
# ---------------- SAFETY LAYER ----------------
def static_code_check(code):
patterns = [
r"\bos\b",
r"\bsubprocess\b",
r"\beval\b",
r"\bexec\b",
r"\bopen\s*\(",
r"\b__import__\b",
r"while\s+True",
r"for\s+.*range\s*\(\s*10\*\*",
]
for p in patterns:
if re.search(p, code):
return False, f"Blocked pattern: {p}"
return True, "OK"
def ai_code_check(code):
try:
with open(CONFIG_PATH, 'r') as f:
config = json.load(f)
client = genai.Client(api_key=config['api_key'])
prompt = f"""
You are a strict code safety filter.
Decide if this code is SAFE to execute.
Unsafe if:
- file access
- OS/system calls
- network calls
- infinite loops
- abuse patterns
Code:
{code}
Return ONLY JSON:
{{
"safe": true/false,
"reason": "short reason"
}}
"""
res = client.models.generate_content(
model="gemini-flash-latest",
contents=prompt
)
raw = res.text.strip()
# Strip markdown fences if present
match = re.search(r'\{[^}]+\}', raw)
if match:
try:
data = json.loads(match.group())
return data.get("safe", True), data.get("reason", "")
except:
pass
# If AI response is unparseable, defer to static check (already passed)
return True, "AI check inconclusive, static check passed"
except Exception as e:
# Network/API errors shouldn't block execution if static check passed
return True, f"AI check skipped: {str(e)}"
# ---------------- PING ----------------
@app.route('/ping')
def ping():
return jsonify({"ok": True})
# ---------------- CONFIG ----------------
@app.route('/save_config', methods=['POST'])
def save_config():
with open(CONFIG_PATH, 'w') as f:
json.dump(request.json, f)
return jsonify({"status": "API Key Saved"})
# ---------------- WORKSPACE ----------------
@app.route('/save_workspace', methods=['POST'])
def save_workspace():
try:
with open('workspace_state.json', 'w') as f:
json.dump(request.json, f, indent=2)
return jsonify({"status": "success"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/load_workspace', methods=['GET'])
def load_workspace():
if os.path.exists('workspace_state.json'):
with open('workspace_state.json', 'r') as f:
return jsonify(json.load(f))
return jsonify({"tabs": {}})
# ---------------- LEETCODE ----------------
def query_leetcode(query, variables=None):
url = "https://leetcode.com/graphql"
r = requests.post(url, json={'query': query, 'variables': variables})
return r.json()
@app.route('/get_leetcode_problems', methods=['GET'])
def get_leetcode_list():
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, 'r') as f:
return jsonify(json.load(f))
try:
r = requests.get("https://leetcode.com/api/problems/all/", headers={'User-Agent': 'Mozilla/5.0'})
data = r.json()
problems = [
{"title": p['stat']['question__title'], "titleSlug": p['stat']['question__title_slug']}
for p in data['stat_status_pairs']
]
with open(CACHE_FILE, 'w') as f:
json.dump(problems, f)
return jsonify(problems)
except:
return jsonify([{"title": "Two Sum", "titleSlug": "two-sum"}])
@app.route('/get_problem_details', methods=['POST'])
def get_details():
slug = request.json.get('slug')
query = """
query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
content
}
}
"""
data = query_leetcode(query, {"titleSlug": slug})
return jsonify({"content": data['data']['question']['content']})
# ---------------- AI FEATURES ----------------
def get_client():
with open(CONFIG_PATH, 'r') as f:
config = json.load(f)
return genai.Client(api_key=config['api_key'])
@app.route('/generate_boilerplate', methods=['POST'])
def generate_boilerplate():
try:
data = request.json
statement = data.get('statement', '')
language = data.get('language', 'python')
# 🧠 Pull user thinking from frontend (if available)
steps = data.get('steps', {})
s1 = steps.get('s1', '')
s2 = steps.get('s2', '')
s3 = steps.get('s3', '')
s4 = steps.get('s4', '')
client = get_client()
prompt = f"""
ROLE: Senior Software Engineer generating CLEAN BOILERPLATE.
IMPORTANT:
- DO NOT solve the problem
- DO NOT implement full logic
- ONLY create structure + placeholders
---------------- PROBLEM ----------------
{statement}
---------------- USER THINKING ----------------
Absorption:
{s1}
Pattern:
{s2}
Pseudocode:
{s3}
Dry Run:
{s4}
---------------- TARGET ----------------
Language: {language}
---------------- RULES ----------------
GENERAL:
- Use function name: solve
- Leave TODO comments for logic
- Keep structure clean and runnable
PYTHON:
- def solve(input_data):
- include if __name__ == "__main__"
JAVA:
- MUST include:
public class Main
public static void main(String[] args)
- include solve() method
- use Scanner for input
- DO NOT use class Solution
JAVASCRIPT:
- function solve(input)
- simple stdin handling (Node style)
OUTPUT:
- ONLY code
- NO explanation
"""
res = client.models.generate_content(
model="gemini-flash-latest",
contents=prompt
)
code = res.text.replace("```", "").strip()
return jsonify({"code": code})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/solve', methods=['POST'])
def solve_problem():
client = get_client()
problem = request.json.get('problem')
res = client.models.generate_content(
model="gemini-flash-latest",
contents=f"Explain optimal approach:\n{problem}"
)
return jsonify({"analysis": res.text})
@app.route('/validate_step', methods=['POST'])
def validate_step():
client = get_client()
data = request.json
prompt = f"""
Problem: {data.get('statement')}
Step: {data.get('step')}
Input: {data.get('content')}
Give short feedback (<60 words)
"""
res = client.models.generate_content(
model="gemini-flash-latest",
contents=prompt
)
return jsonify({"feedback": res.text})
@app.route('/generate_test_data', methods=['POST'])
def generate_test_data():
try:
client = get_client()
data = request.json
statement = data.get('statement')
code = data.get('code')
lang = data.get('language')
prompt = f"""
You are an expert SDET. Generate comprehensive unit tests for the following problem and code.
PROBLEM: {statement}
LANGUAGE: {lang}
USER CODE:
{code}
REQUIREMENTS:
1. Write a test runner script that tests multiple edge cases (empty, large, negatives, etc.).
2. The runner MUST print a formatted plain text tabular view of what failed/passed to stdout.
Example format:
| Test Case | Expected | Actual | Status |
|-----------|----------|--------|--------|
| [1,2] | 3 | 3 | PASS |
3. The code you return will be concatenated to the bottom of the User Code.
4. For Python: Write plain script logic that calls the user's function.
5. For JavaScript: Write plain script logic that calls the user's function.
6. For Java: Create a `class TestRunner {{ public static void main(String[] args) {{ ... }} }}`.
7. ONLY return the raw code. NO markdown formatting, NO explanations.
"""
res = client.models.generate_content(
model="gemini-flash-latest",
contents=prompt
)
test_script = res.text.replace("```python", "").replace("```javascript", "").replace("```java", "").replace("```", "").strip()
return jsonify({"test_script": test_script})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------- EXECUTION (UPDATED WITH SAFETY) ----------------
@app.route('/sanity_check', methods=['POST'])
def sanity_check():
try:
code = request.json.get('code', '')
code_hash = hashlib.md5(code.encode('utf-8')).hexdigest()
if code_hash in safe_code_hashes:
return jsonify({"safe": True, "reason": "cached"})
ok, msg = static_code_check(code)
if not ok:
return jsonify({"safe": False, "reason": msg})
safe, reason = ai_code_check(code)
if not safe:
return jsonify({"safe": False, "reason": reason})
safe_code_hashes.add(code_hash)
return jsonify({"safe": True, "reason": "OK"})
except Exception as e:
return jsonify({"safe": False, "reason": str(e)})
@app.route('/run_code', methods=['POST'])
def run_code():
try:
code = request.json.get('code')
lang = request.json.get('language')
code_hash = hashlib.md5(code.encode('utf-8')).hexdigest()
if code_hash not in safe_code_hashes:
# ---- STATIC CHECK ----
ok, msg = static_code_check(code)
if not ok:
return jsonify({"output": f"[BLOCKED - STATIC]\n{msg}", "success": False})
# ---- AI CHECK ----
safe, reason = ai_code_check(code)
if not safe:
return jsonify({"output": f"[BLOCKED - AI]\n{reason}", "success": False})
safe_code_hashes.add(code_hash)
with tempfile.TemporaryDirectory() as tmpdir:
if lang == 'Python':
path = os.path.join(tmpdir, "main.py")
with open(path, 'w') as f:
f.write(code)
result = subprocess.run(
["python3", "-I", path],
capture_output=True,
text=True,
timeout=15
)
elif lang == 'Java':
m = re.search(r'public\s+class\s+(\w+)', code)
cls_name = m.group(1) if m else 'Main'
path = os.path.join(tmpdir, cls_name + '.java')
with open(path, 'w') as f:
f.write(code)
compile_res = subprocess.run(['javac', path], capture_output=True, text=True)
if compile_res.returncode != 0:
return jsonify({"output": compile_res.stderr, "success": False})
main_class = 'TestRunner' if 'class TestRunner' in code else cls_name
result = subprocess.run(['java', '-cp', tmpdir, main_class], capture_output=True, text=True, timeout=30)
elif lang == 'JavaScript':
path = os.path.join(tmpdir, "solution.js")
with open(path, 'w') as f:
f.write(code)
result = subprocess.run(['node', path], capture_output=True, text=True, timeout=15)
else:
return jsonify({"output": "Unsupported language", "success": False})
output = result.stdout or result.stderr
return jsonify({
"output": output,
"success": result.returncode == 0
})
except subprocess.TimeoutExpired:
return jsonify({"output": "[TIMEOUT] Infinite loop suspected", "success": False})
except Exception as e:
return jsonify({"output": str(e), "success": False})
@app.route('/chat', methods=['POST'])
def chat():
try:
client = get_client()
data = request.json
question = data.get('question', '')
selection = data.get('selection', '')
source = data.get('source', '')
statement = data.get('statement', '')
ref_context = data.get('refContext', '')
prompt = f"""You are a concise coding tutor. Answer in <100 words.
Problem: {statement[:500]}
Selected text from [{source}]: {selection[:500]}
{('Referenced threads:\n' + ref_context) if ref_context else ''}
Question: {question}"""
res = client.models.generate_content(
model="gemini-flash-latest",
contents=prompt
)
return jsonify({"answer": res.text})
except Exception as e:
return jsonify({"answer": f"Error: {str(e)}"}), 500
# ---------------- GEMINI PROXY ----------------
@app.route('/gemini_proxy', methods=['POST'])
def gemini_proxy():
try:
data = request.json
api_key = data.get('api_key', '')
prompt = data.get('prompt', '')
if not api_key:
return jsonify({"error": "No API key provided"}), 400
client = genai.Client(api_key=api_key)
res = client.models.generate_content(model="gemini-flash-latest", contents=prompt)
return jsonify({"text": res.text})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------- FRONTEND ----------------
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8500, debug=True)