-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
638 lines (507 loc) · 19 KB
/
Copy pathapp.py
File metadata and controls
638 lines (507 loc) · 19 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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import os
from functools import wraps
from flask import (
Flask,
render_template,
request,
redirect,
url_for,
flash,
session,
jsonify,
)
from flask_mysqldb import MySQL
from werkzeug.security import generate_password_hash, check_password_hash
from dotenv import load_dotenv
from openai import OpenAI
import time
import json
import requests
load_dotenv()
app = Flask(__name__)
# MySQL configuration (can also be overridden from .env)
app.config['MYSQL_HOST'] = os.getenv('MYSQL_HOST', 'localhost')
app.config['MYSQL_USER'] = os.getenv('MYSQL_USER', 'root')
app.config['MYSQL_PASSWORD'] = os.getenv('MYSQL_PASSWORD', 'root')
app.config['MYSQL_DB'] = os.getenv('MYSQL_DB', 'code')
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# Secret key for sessions
app.secret_key = os.getenv('SECRET_KEY', 'dont tell any one')
mysql = MySQL(app)
# OpenAI client
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None
# Languages for converter
LANGUAGES = [
"Python",
"Java",
"JavaScript",
"C",
"C++",
"C#",
"PHP",
"Ruby",
"Go",
"Dart",
"Kotlin",
"Swift",
"Rust",
]
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
flash("Please log in to continue.", "warning")
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def call_gpt(system_prompt: str, user_prompt: str) -> str:
"""Helper to call the OpenAI chat completion API."""
if not client:
return "OpenAI API key not configured. Set OPENAI_API_KEY in your .env file."
try:
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=0.2,
)
return response.choices[0].message.content.strip()
except Exception as e:
print("OpenAI API error:", e)
return "Error while talking to the AI model. Please try again later."
# ---------------------- Auth routes ----------------------
@app.route("/")
def index():
return render_template("index.html")
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
username = request.form.get("username", "").strip()
email = request.form.get("email", "").strip()
password = request.form.get("password", "")
confirm = request.form.get("confirm_password", "")
if not username or not email or not password:
flash("All fields are required.", "danger")
return redirect(url_for('signup'))
if password != confirm:
flash("Passwords do not match.", "danger")
return redirect(url_for('signup'))
pw_hash = generate_password_hash(password)
cur = mysql.connection.cursor()
try:
cur.execute(
"INSERT INTO users (username, email, password_hash) VALUES (%s, %s, %s)",
(username, email, pw_hash),
)
mysql.connection.commit()
flash("Account created. Please log in.", "success")
return redirect(url_for('login'))
except Exception as e:
mysql.connection.rollback()
print("Signup error:", e)
flash("Error creating account. Maybe this email is already registered?", "danger")
finally:
cur.close()
return render_template("signup.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email", "").strip()
password = request.form.get("password", "")
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
user = cur.fetchone()
cur.close()
if user and check_password_hash(user["password_hash"], password):
session["user_id"] = user["id"]
session["username"] = user["username"]
flash("Logged in successfully.", "success")
return redirect(url_for("dashboard"))
else:
flash("Invalid email or password.", "danger")
return render_template("login.html")
@app.route("/logout")
def logout():
session.clear()
flash("You have been logged out.", "info")
return redirect(url_for("index"))
# ---------------------- Dashboard ----------------------
@app.route("/dashboard")
@login_required
def dashboard():
return render_template("dashboard.html")
# ---------------------- Code Converter ----------------------
@app.route("/convert", methods=["GET", "POST"])
@login_required
def convert():
output_code = None
source_language = ""
target_language = ""
code = ""
if request.method == "POST":
source_language = request.form.get("source_language") or ""
target_language = request.form.get("target_language") or ""
code = request.form.get("code") or ""
system_prompt = "You are an expert multilingual programming assistant. You convert code between languages accurately."
user_prompt = (
f"Convert the following {source_language} code into {target_language}. "
"Return only valid {target_language} code, no explanation.\n\n"
f"{code}"
)
# Fix target language placeholder in prompt
user_prompt = user_prompt.replace("{target_language}", target_language)
output_code = call_gpt(system_prompt, user_prompt)
# Save to history
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO history (user_id, feature, input_language, output_language, input_code, output_text) "
"VALUES (%s, %s, %s, %s, %s, %s)",
(session["user_id"], "convert", source_language, target_language, code, output_code),
)
mysql.connection.commit()
cur.close()
return render_template(
"convert.html",
languages=LANGUAGES,
output_code=output_code,
source_language=source_language,
target_language=target_language,
code=code,
)
# ---------------------- Debugging ----------------------
@app.route("/debug", methods=["GET", "POST"])
@login_required
def debug():
result = None
language = ""
code = ""
if request.method == "POST":
language = request.form.get("language") or ""
code = request.form.get("code") or ""
system_prompt = "You are a strict but friendly code reviewer and debugger."
user_prompt = (
f"Find and explain syntax errors, runtime errors, and common logical bugs in the following {language} code. "
"Suggest a corrected version and short explanations.\n\n"
f"{code}"
)
result = call_gpt(system_prompt, user_prompt)
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO history (user_id, feature, input_language, input_code, output_text) "
"VALUES (%s, %s, %s, %s, %s)",
(session["user_id"], "debug", language, code, result),
)
mysql.connection.commit()
cur.close()
return render_template(
"debug.html",
languages=LANGUAGES,
result=result,
language=language,
code=code,
)
# ---------------------- Explain Code ----------------------
@app.route("/explain", methods=["GET", "POST"])
@login_required
def explain():
explanation = None
language = ""
code = ""
if request.method == "POST":
language = request.form.get("language") or ""
code = request.form.get("code") or ""
system_prompt = "You are a friendly senior developer who explains code to beginners."
user_prompt = (
f"Explain in clear, simple language what the following {language} code does. "
"Use headings and bullet points where helpful.\n\n"
f"{code}"
)
explanation = call_gpt(system_prompt, user_prompt)
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO history (user_id, feature, input_language, input_code, output_text) "
"VALUES (%s, %s, %s, %s, %s)",
(session["user_id"], "explain", language, code, explanation),
)
mysql.connection.commit()
cur.close()
return render_template(
"explain.html",
languages=LANGUAGES,
explanation=explanation,
language=language,
code=code,
)
# ---------------------- Pseudocode / Flowchart ----------------------
@app.route("/pseudocode", methods=["GET", "POST"])
@login_required
def pseudocode():
output = None
language = ""
code = ""
if request.method == "POST":
language = request.form.get("language") or ""
code = request.form.get("code") or ""
system_prompt = "You are great at turning real code into clean pseudocode and flowchart steps."
user_prompt = (
f"Convert the following {language} code into high-level pseudocode and outline the logic as numbered steps "
"that could be used to draw a flowchart. Respond in two clear sections:\n"
"1) Pseudocode\n2) Flowchart Steps\n\n"
f"{code}"
)
output = call_gpt(system_prompt, user_prompt)
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO history (user_id, feature, input_language, input_code, output_text) "
"VALUES (%s, %s, %s, %s, %s)",
(session["user_id"], "pseudocode", language, code, output),
)
mysql.connection.commit()
cur.close()
return render_template(
"pseudocode.html",
languages=LANGUAGES,
output=output,
language=language,
code=code,
)
# ---------------------- Complexity / Big-O ----------------------
@app.route("/complexity", methods=["GET", "POST"])
@login_required
def complexity():
analysis = None
language = ""
code = ""
if request.method == "POST":
language = request.form.get("language") or ""
code = request.form.get("code") or ""
system_prompt = "You are an algorithms expert. You analyze time and space complexity."
user_prompt = (
f"Analyze the Big-O time and space complexity of the following {language} code. "
"Explain your reasoning and, if possible, suggest a more efficient approach.\n\n"
f"{code}"
)
analysis = call_gpt(system_prompt, user_prompt)
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO history (user_id, feature, input_language, input_code, output_text) "
"VALUES (%s, %s, %s, %s, %s)",
(session["user_id"], "complexity", language, code, analysis),
)
mysql.connection.commit()
cur.close()
return render_template(
"complexity.html",
languages=LANGUAGES,
analysis=analysis,
language=language,
code=code,
)
# ---------------------- Performance Optimization ----------------------
@app.route("/optimize", methods=["GET", "POST"])
@login_required
def optimize():
suggestions = None
language = ""
code = ""
if request.method == "POST":
language = request.form.get("language") or ""
code = request.form.get("code") or ""
system_prompt = "You are a performance engineer. You find and fix slow code."
user_prompt = (
f"Detect any performance bottlenecks in the following {language} code. "
"Explain why they are slow and show an optimized version with comments.\n\n"
f"{code}"
)
suggestions = call_gpt(system_prompt, user_prompt)
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO history (user_id, feature, input_language, input_code, output_text) "
"VALUES (%s, %s, %s, %s, %s)",
(session["user_id"], "optimize", language, code, suggestions),
)
mysql.connection.commit()
cur.close()
return render_template(
"optimize.html",
languages=LANGUAGES,
suggestions=suggestions,
language=language,
code=code,
)
# ---------------------- Chat Feature ----------------------
@app.route("/chat")
@login_required
def chat():
return render_template("chat.html")
@app.route("/api/chat", methods=["POST"])
@login_required
def api_chat():
data = request.get_json(silent=True) or {}
message = (data.get("message") or "").strip()
if not message:
return jsonify({"error": "Message cannot be empty."}), 400
system_prompt = "You are CodeMate, a friendly and concise AI coding assistant."
reply = call_gpt(system_prompt, message)
# Save chat to DB
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO chats (user_id, user_message, assistant_message) VALUES (%s, %s, %s)",
(session["user_id"], message, reply),
)
mysql.connection.commit()
cur.close()
return jsonify({"reply": reply})
# ---------------------- History ----------------------
# ---------------------- Online Compiler (Judge0) ----------------------
JUDGE0_URL = (os.getenv("JUDGE0_URL") or "https://ce.judge0.com").rstrip("/")
JUDGE0_AUTH_TOKEN = (os.getenv("JUDGE0_AUTH_TOKEN") or "").strip()
_LANG_CACHE = {"ts": 0.0, "items": []} # cache Judge0 languages for 1 hour
def judge0_headers() -> dict:
headers = {"Content-Type": "application/json"}
# Judge0 can be configured to require X-Auth-Token on the instance you use. :contentReference[oaicite:2]{index=2}
if JUDGE0_AUTH_TOKEN:
headers["X-Auth-Token"] = JUDGE0_AUTH_TOKEN
return headers
def judge0_languages() -> list[dict]:
"""Fetch supported languages from Judge0 (cached). Endpoint: GET /languages/ :contentReference[oaicite:3]{index=3}"""
now = time.time()
if _LANG_CACHE["items"] and (now - _LANG_CACHE["ts"] < 3600):
return _LANG_CACHE["items"]
resp = requests.get(f"{JUDGE0_URL}/languages/", headers=judge0_headers(), timeout=15)
resp.raise_for_status()
_LANG_CACHE["items"] = resp.json()
_LANG_CACHE["ts"] = now
return _LANG_CACHE["items"]
def judge0_language_id_from_name(app_language: str) -> int | None:
"""
Map your UI language string (e.g., 'Python', 'C++') to Judge0 language_id.
Judge0 language names include versions, so we match by prefix/base name.
"""
wanted = (app_language or "").strip().lower()
if not wanted:
return None
# small synonym normalization
synonyms = {
"javascript": ["javascript", "node", "node.js"],
"c++": ["c++", "cpp"],
"c#": ["c#", "csharp"],
}
wanted_aliases = [wanted] + synonyms.get(wanted, [])
langs = judge0_languages()
for lang in langs:
name = (lang.get("name") or "").lower()
base = name.split(" (", 1)[0].strip() # "Python (3.11.2)" -> "python"
for w in wanted_aliases:
if base == w or name.startswith(w):
return lang.get("id")
return None
def judge0_submit_and_wait(language_id: int, source_code: str, stdin: str = "") -> dict:
"""
Create submission (POST /submissions?wait=false) then poll GET /submissions/{token}.
Docs note: wait=true is not recommended for scaling; polling is preferred. :contentReference[oaicite:4]{index=4}
"""
payload = {
"language_id": language_id,
"source_code": source_code,
"stdin": stdin or "",
}
# Create submission endpoint shown in docs. :contentReference[oaicite:5]{index=5}
create = requests.post(
f"{JUDGE0_URL}/submissions/?base64_encoded=false&wait=false",
headers=judge0_headers(),
json=payload,
timeout=20,
)
create.raise_for_status()
token = create.json().get("token")
if not token:
raise RuntimeError("Judge0 did not return a submission token.")
# Poll until done: status.id > 2 (1=in queue, 2=processing are common)
last = {}
for _ in range(40): # ~20s if sleep=0.5
r = requests.get(
f"{JUDGE0_URL}/submissions/{token}?base64_encoded=false&fields=*",
headers=judge0_headers(),
timeout=20,
)
r.raise_for_status()
last = r.json()
status = last.get("status") or {}
status_id = status.get("id") or last.get("status_id")
if status_id is not None and int(status_id) > 2:
break
time.sleep(0.5)
return last
@app.route("/compile", methods=["GET", "POST"])
@login_required
def compile():
result = None
code = ""
stdin = ""
# Fetch Judge0 languages for dropdown (id + name)
try:
judge0_langs = judge0_languages() # list of dicts: {"id":..., "name":...}
except Exception as e:
print("Judge0 languages fetch error:", e)
judge0_langs = []
if request.method == "POST":
code = request.form.get("code") or ""
stdin = request.form.get("stdin") or ""
language_id = request.form.get("language_id") # <-- ID from dropdown
if not code.strip():
flash("Code cannot be empty.", "danger")
return redirect(url_for("compile"))
if not language_id:
flash("Please select a language.", "danger")
return redirect(url_for("compile"))
try:
language_id = int(language_id)
raw = judge0_submit_and_wait(language_id, code, stdin)
result = {
"status": (raw.get("status") or {}).get("description"),
"stdout": raw.get("stdout") or "",
"stderr": raw.get("stderr") or "",
"compile_output": raw.get("compile_output") or "",
"message": raw.get("message") or "",
"time": raw.get("time"),
"memory": raw.get("memory"),
}
# Save to history
import json
cur = mysql.connection.cursor()
cur.execute(
"INSERT INTO history (user_id, feature, input_language, input_code, output_text) "
"VALUES (%s, %s, %s, %s, %s)",
(session["user_id"], "compile", str(language_id), code, json.dumps(result)),
)
mysql.connection.commit()
cur.close()
except Exception as e:
print("Compile error:", e)
flash("Error running code on compiler service.", "danger")
return render_template(
"compile.html",
judge0_langs=judge0_langs,
result=result,
code=code,
stdin=stdin,
)
@app.route("/history")
@login_required
def history():
cur = mysql.connection.cursor()
cur.execute(
"SELECT id, feature, input_language, output_language, created_at "
"FROM history WHERE user_id = %s "
"ORDER BY created_at DESC LIMIT 50",
(session["user_id"],),
)
rows = cur.fetchall()
cur.close()
return render_template("history.html", history_rows=rows)
if __name__ == "__main__":
app.run(debug=True)