Mananjp commited on
Commit
24a26be
Β·
1 Parent(s): ebb5c56

feat: LeetCode split-pane layout + auto-block after 3 violations

Browse files
Files changed (2) hide show
  1. backend/main.py +34 -4
  2. frontend/app.py +479 -453
backend/main.py CHANGED
@@ -39,6 +39,9 @@ code_executor = CodeExecutor()
39
  # Max score per question (each question is worth this many points)
40
  MAX_SCORE_PER_QUESTION = 100
41
 
 
 
 
42
 
43
  # ============================================================================
44
  # HELPER: Room expiry check
@@ -103,7 +106,7 @@ async def create_room(data: dict):
103
 
104
  @app.post("/api/rooms/{room_id}/report_violation")
105
  async def report_violation(room_id: str, data: dict):
106
- """Report a student violation (tab switch, etc.)"""
107
  student_id = data.get("student_id")
108
 
109
  room = await db.get_room(room_id)
@@ -116,7 +119,9 @@ async def report_violation(room_id: str, data: dict):
116
  new_flags = current_flags + 1
117
  await db.update_red_flags(room_id, student_id, new_flags)
118
 
119
- return {"success": True, "new_count": new_flags}
 
 
120
 
121
  return {"success": False}
122
 
@@ -134,6 +139,10 @@ async def get_room(room_id: str):
134
  await db.expire_room(room_id)
135
  status = "expired"
136
 
 
 
 
 
137
  return {
138
  "room_id": room["room_id"],
139
  "room_code": room["room_code"],
@@ -146,7 +155,8 @@ async def get_room(room_id: str):
146
  "duration_minutes": room.get("duration_minutes"),
147
  "start_time": room.get("start_time"),
148
  "end_time": room.get("end_time"),
149
- "student_red_flags": room.get("student_red_flags", {}),
 
150
  "status": status
151
  }
152
 
@@ -254,7 +264,7 @@ async def get_worksheet(room_id: str, student_id: str, question_id: str):
254
 
255
  @app.post("/api/worksheets/{worksheet_id}/save")
256
  async def save_worksheet(worksheet_id: str, data: dict):
257
- """Save worksheet code. BLOCKED if room is expired."""
258
  # Check if the worksheet's room is still active
259
  ws = await db.get_worksheet_by_id(worksheet_id)
260
  if not ws:
@@ -266,6 +276,13 @@ async def save_worksheet(worksheet_id: str, data: dict):
266
  await db.expire_room(room["room_id"])
267
  raise HTTPException(status_code=403, detail="Exam has ended. Cannot save code.")
268
 
 
 
 
 
 
 
 
269
  success = await db.save_worksheet(worksheet_id, data.get("code", ""))
270
 
271
  if not success:
@@ -322,6 +339,11 @@ async def submit_solution(data: dict):
322
  await db.expire_room(room_id)
323
  raise HTTPException(status_code=403, detail="Exam has ended. Cannot submit solutions.")
324
 
 
 
 
 
 
325
  # Get the question with ALL test cases (including hidden)
326
  question = await db.get_question(room_id, question_id)
327
  if not question:
@@ -433,10 +455,13 @@ async def get_room_scores(room_id: str):
433
 
434
  scores_data = []
435
  for sid in students:
 
 
436
  student_entry = {
437
  "student_id": sid,
438
  "student_name": student_names.get(sid, "Unknown"),
439
  "red_flags": student_red_flags.get(sid, 0),
 
440
  "questions": [],
441
  "total_score": 0,
442
  "max_total": len(questions) * MAX_SCORE_PER_QUESTION
@@ -460,6 +485,11 @@ async def get_room_scores(room_id: str):
460
  elif status != "accepted":
461
  status = "attempted"
462
 
 
 
 
 
 
463
  student_entry["questions"].append({
464
  "question_id": qid,
465
  "score": best_score,
 
39
  # Max score per question (each question is worth this many points)
40
  MAX_SCORE_PER_QUESTION = 100
41
 
42
+ # Violation threshold: if a student exceeds this many violations, they are blocked
43
+ MAX_VIOLATIONS_ALLOWED = 3
44
+
45
 
46
  # ============================================================================
47
  # HELPER: Room expiry check
 
106
 
107
  @app.post("/api/rooms/{room_id}/report_violation")
108
  async def report_violation(room_id: str, data: dict):
109
+ """Report a student violation (tab switch, etc.). Auto-blocks after threshold."""
110
  student_id = data.get("student_id")
111
 
112
  room = await db.get_room(room_id)
 
119
  new_flags = current_flags + 1
120
  await db.update_red_flags(room_id, student_id, new_flags)
121
 
122
+ blocked = new_flags > MAX_VIOLATIONS_ALLOWED
123
+
124
+ return {"success": True, "new_count": new_flags, "blocked": blocked}
125
 
126
  return {"success": False}
127
 
 
139
  await db.expire_room(room_id)
140
  status = "expired"
141
 
142
+ # Compute blocked students list
143
+ student_red_flags = room.get("student_red_flags", {})
144
+ blocked_students = [sid for sid, flags in student_red_flags.items() if flags > MAX_VIOLATIONS_ALLOWED]
145
+
146
  return {
147
  "room_id": room["room_id"],
148
  "room_code": room["room_code"],
 
155
  "duration_minutes": room.get("duration_minutes"),
156
  "start_time": room.get("start_time"),
157
  "end_time": room.get("end_time"),
158
+ "student_red_flags": student_red_flags,
159
+ "blocked_students": blocked_students,
160
  "status": status
161
  }
162
 
 
264
 
265
  @app.post("/api/worksheets/{worksheet_id}/save")
266
  async def save_worksheet(worksheet_id: str, data: dict):
267
+ """Save worksheet code. BLOCKED if room is expired or student is blocked."""
268
  # Check if the worksheet's room is still active
269
  ws = await db.get_worksheet_by_id(worksheet_id)
270
  if not ws:
 
276
  await db.expire_room(room["room_id"])
277
  raise HTTPException(status_code=403, detail="Exam has ended. Cannot save code.")
278
 
279
+ # Check if student is blocked due to violations
280
+ if room:
281
+ student_id = ws.get("student_id")
282
+ student_flags = room.get("student_red_flags", {}).get(student_id, 0)
283
+ if student_flags > MAX_VIOLATIONS_ALLOWED:
284
+ raise HTTPException(status_code=403, detail="You have been blocked from this exam due to repeated violations. Your score is 0.")
285
+
286
  success = await db.save_worksheet(worksheet_id, data.get("code", ""))
287
 
288
  if not success:
 
339
  await db.expire_room(room_id)
340
  raise HTTPException(status_code=403, detail="Exam has ended. Cannot submit solutions.")
341
 
342
+ # Check if student is blocked due to violations
343
+ student_flags = room.get("student_red_flags", {}).get(student_id, 0)
344
+ if student_flags > MAX_VIOLATIONS_ALLOWED:
345
+ raise HTTPException(status_code=403, detail="You have been blocked from this exam due to repeated violations. Your score is 0.")
346
+
347
  # Get the question with ALL test cases (including hidden)
348
  question = await db.get_question(room_id, question_id)
349
  if not question:
 
455
 
456
  scores_data = []
457
  for sid in students:
458
+ is_blocked = student_red_flags.get(sid, 0) > MAX_VIOLATIONS_ALLOWED
459
+
460
  student_entry = {
461
  "student_id": sid,
462
  "student_name": student_names.get(sid, "Unknown"),
463
  "red_flags": student_red_flags.get(sid, 0),
464
+ "blocked": is_blocked,
465
  "questions": [],
466
  "total_score": 0,
467
  "max_total": len(questions) * MAX_SCORE_PER_QUESTION
 
485
  elif status != "accepted":
486
  status = "attempted"
487
 
488
+ # Override scores to 0 if student is blocked
489
+ if is_blocked:
490
+ best_score = 0
491
+ status = "blocked"
492
+
493
  student_entry["questions"].append({
494
  "question_id": qid,
495
  "score": best_score,
frontend/app.py CHANGED
@@ -696,8 +696,7 @@ def teacher_page(api_client):
696
 
697
 
698
  def student_page(api_client):
699
- """Student workspace"""
700
- st.title("πŸ’» Student Workspace")
701
 
702
  # Sidebar for room joining
703
  with st.sidebar:
@@ -722,259 +721,405 @@ def student_page(api_client):
722
  else:
723
  st.error(f"Error: {e}")
724
  except Exception as e:
725
- # The API might return 403 as JSON
726
  st.error(f"Error: {e}")
727
 
728
- if "room_id" in st.session_state:
729
- st.info(f"βœ… Connected as **{st.session_state.student_name}**")
730
-
731
- # Get room details to check timing
732
- try:
733
- room = api_client.get_room(st.session_state.room_id)
734
- start_time_str = room.get("start_time")
735
- end_time_str = room.get("end_time")
736
-
737
- now = datetime.now()
738
- start_time = datetime.fromisoformat(start_time_str) if start_time_str else None
739
- end_time = datetime.fromisoformat(end_time_str) if end_time_str else None
740
-
741
- if start_time and now < start_time:
742
- st.warning(f"Exam has not started yet. Start time: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
743
- time_diff = start_time - now
744
- st.metric("Time until start", str(time_diff).split('.')[0])
745
- if st.button("Refresh Status"):
746
- st.rerun()
747
- return
748
-
749
- if end_time and now > end_time:
750
- st.error("Exam has ended. You can no longer submit code.")
751
- st.metric("Exam Ended", end_time.strftime('%Y-%m-%d %H:%M:%S'))
752
- return
753
-
754
- # EXAM IN PROGRESS
755
- if end_time:
756
- time_left = end_time - now
757
-
758
- st_room_id = st.session_state.room_id
759
- st_student_id = st.session_state.student_id
760
-
761
- security_script = f"""
762
- <script>
763
- const targetWindow = window.parent;
764
- const targetDocument = targetWindow.document;
765
-
766
- function reportViolation() {{
767
- fetch("{PUBLIC_BACKEND_URL}/api/rooms/{st_room_id}/report_violation", {{
768
- method: "POST",
769
- headers: {{
770
- "Content-Type": "application/json"
771
- }},
772
- body: JSON.stringify({{
773
- "student_id": "{st_student_id}"
774
- }})
775
- }}).catch(e => console.error(e));
776
- }}
777
-
778
- function requestFullScreen() {{
779
- var elem = targetDocument.documentElement;
780
- if (elem.requestFullscreen) {{
781
- elem.requestFullscreen().catch(err => {{
782
- console.log("Error attempting to enable full-screen mode: " + err.message);
783
- }});
784
- }} else if (elem.webkitRequestFullscreen) {{
785
- elem.webkitRequestFullscreen();
786
- }} else if (elem.msRequestFullscreen) {{
787
- elem.msRequestFullscreen();
788
- }}
789
- }}
790
-
791
- function showOverlay(message, isRed = true) {{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792
  var overlay = targetDocument.getElementById('security-overlay');
793
- if (!overlay) {{
794
- overlay = targetDocument.createElement('div');
795
- overlay.id = 'security-overlay';
796
- overlay.style.position = 'fixed';
797
- overlay.style.top = '0';
798
- overlay.style.left = '0';
799
- overlay.style.width = '100vw';
800
- overlay.style.height = '100vh';
801
- overlay.style.zIndex = '999999';
802
- overlay.style.color = 'white';
803
- overlay.style.display = 'flex';
804
- overlay.style.justifyContent = 'center';
805
- overlay.style.alignItems = 'center';
806
- overlay.style.flexDirection = 'column';
807
-
808
- overlay.onclick = function() {{
809
- overlay.style.display = 'none';
810
- targetDocument.title = "Online Exam IDE";
811
- requestFullScreen();
812
- }};
813
-
814
- targetDocument.body.appendChild(overlay);
815
- }}
816
-
817
- overlay.style.backgroundColor = isRed ? 'rgba(255, 0, 0, 0.98)' : 'rgba(0, 0, 0, 0.9)';
818
- overlay.innerHTML = message;
819
- overlay.style.display = 'flex';
820
  }}
821
-
822
- targetDocument.addEventListener('contextmenu', event => {{
823
- event.preventDefault();
824
- event.stopPropagation();
825
- reportViolation();
826
- showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">Right-click is forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
827
- return false;
828
- }}, true);
829
-
830
- targetDocument.addEventListener('keydown', function(e) {{
831
- if (e.ctrlKey || e.altKey || e.metaKey) {{
832
- e.preventDefault();
833
- e.stopPropagation();
834
- reportViolation();
835
- showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">Keyboard shortcuts are forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
836
- return false;
837
- }}
838
- if (e.keyCode >= 112 && e.keyCode <= 123) {{
839
- e.preventDefault();
840
- e.stopPropagation();
841
- reportViolation();
842
- showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">Function keys are forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
843
- return false;
844
- }}
845
- }}, true);
846
-
847
- ['copy', 'cut', 'paste'].forEach(e => {{
848
- targetDocument.addEventListener(e, function(event) {{
849
- event.preventDefault();
850
- event.stopPropagation();
851
- reportViolation();
852
- let action = e.toUpperCase();
853
- showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">' + action + ' is forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
854
- return false;
855
- }}, true);
856
  }});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
857
 
858
- targetWindow.addEventListener('blur', function() {{
859
- targetDocument.title = " EXAM WARNING: COME BACK!";
860
- reportViolation();
861
- showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">You left the exam window!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
862
- }});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
863
 
864
- function handleFullscreenChange() {{
865
- if (!targetDocument.fullscreenElement && !targetDocument.webkitFullscreenElement && !targetDocument.msFullscreenElement) {{
866
- reportViolation();
867
- showOverlay('<h1 style="font-size: 40px;"> FULLSCREEN REQUIRED</h1><h2 style="font-size: 25px;">You cannot leave fullscreen mode.</h2><p style="font-size: 20px;">CLICK HERE to return to fullscreen.</p>', true);
868
- }}
869
- }}
870
 
871
- targetDocument.addEventListener('fullscreenchange', handleFullscreenChange);
872
- targetDocument.addEventListener('webkitfullscreenchange', handleFullscreenChange);
873
- targetDocument.addEventListener('mozfullscreenchange', handleFullscreenChange);
874
- targetDocument.addEventListener('MSFullscreenChange', handleFullscreenChange);
875
-
876
- const style = targetDocument.createElement('style');
877
- style.innerHTML = `
878
- [data-testid="stSidebar"] {{ display: none !important; }}
879
- [data-testid="stToolbar"] {{ visibility: hidden !important; }}
880
- header {{ visibility: hidden !important; }}
881
- `;
882
- targetDocument.head.appendChild(style);
883
-
884
- setInterval(function() {{
885
- if (!targetDocument.fullscreenElement && !targetDocument.webkitFullscreenElement && !targetDocument.msFullscreenElement) {{
886
- var overlay = targetDocument.getElementById('security-overlay');
887
- if (!overlay || overlay.style.display == 'none') {{
888
- showOverlay('<h1 style="font-size: 40px;"> FULLSCREEN REQUIRED</h1><h2 style="font-size: 25px;">You cannot leave fullscreen mode.</h2><p style="font-size: 20px;">CLICK HERE to return to fullscreen.</p>', true);
889
- }}
890
- }}
891
- }}, 1000);
892
-
893
- setTimeout(requestFullScreen, 500);
894
- console.log("Security script loaded and attached to parent");
895
- </script>
896
- """
897
- components.html(security_script, height=0, width=0)
898
-
899
- # Top bar
900
- col1, col2, col3 = st.columns([1, 1, 1])
901
- with col1:
902
- st.metric("⏱ Time Remaining", str(time_left).split('.')[0])
903
- with col3:
904
- st.markdown("""
905
- <button onclick="parent.document.documentElement.requestFullscreen()" style="
906
- background-color: #FF4B4B;
907
- color: white;
908
- padding: 10px 20px;
909
- border: none;
910
- border-radius: 5px;
911
- cursor: pointer;
912
- font-weight: bold;">
913
- Force Full Screen
914
- </button>
915
- """, unsafe_allow_html=True)
916
-
917
- if st.button("Refresh Timer"):
918
- st.rerun()
919
 
920
- except Exception as e:
921
- st.error(f"Error checking exam status: {e}")
 
 
 
 
 
 
 
922
 
923
  # ================================================================
924
- # QUESTION + TEST CASES DISPLAY + CODE EDITOR
925
  # ================================================================
926
- try:
927
- questions = api_client.get_questions(st.session_state.room_id)
928
- question_list = questions.get("questions", [])
929
-
930
- if question_list:
931
- # Question selection
932
- question_names = [q.get("question_text", f"Question {i + 1}")[:60] for i, q in enumerate(question_list)]
933
- selected_q_idx = st.selectbox("Select Question", range(len(question_names)),
934
- format_func=lambda i: question_names[i])
935
- selected_question = question_list[selected_q_idx]
936
- question_id = selected_question.get("question_id")
937
-
938
- # Display question text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
939
  st.markdown("---")
940
- st.subheader("πŸ“ Problem Statement")
941
- st.write(f"**{selected_question['question_text']}**")
942
-
943
- language = selected_question.get("language", "Python").lower()
944
-
945
- # ================================================================
946
- # DISPLAY EXAMPLE TEST CASES (visible to students)
947
- # ================================================================
948
- example_test_cases = selected_question.get("test_cases", [])
949
- hidden_count = selected_question.get("hidden_test_cases_count", 0)
950
- total_count = selected_question.get("total_test_cases", 0)
951
-
952
- if example_test_cases or hidden_count > 0:
953
- st.markdown("---")
954
- st.subheader("πŸ§ͺ Test Cases")
955
-
956
- if example_test_cases:
957
- st.write("**Example Test Cases** (visible to you):")
958
- for j, tc in enumerate(example_test_cases):
959
- with st.container():
960
- col_in, col_out = st.columns(2)
961
- with col_in:
962
- st.markdown(f"**Input {j+1}:**")
963
- input_display = tc.get("input_data", "(no input)")
964
- st.code(input_display if input_display else "(no input)", language="text")
965
- with col_out:
966
- st.markdown(f"**Expected Output {j+1}:**")
967
- st.code(tc.get("expected_output", ""), language="text")
968
-
969
- if hidden_count > 0:
970
- st.info(f"πŸ”’ **{hidden_count}** hidden test case(s) will be used for final judging.")
971
 
972
- # ================================================================
973
- # CODE TEMPLATES
974
- # ================================================================
975
- st.divider()
976
- st.subheader("πŸ“‹ Code Templates")
 
 
977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978
  if language in ["python", "py"]:
979
  templates = PYTHON_TEMPLATES
980
  else:
@@ -991,233 +1136,114 @@ def student_page(api_client):
991
  question_id
992
  )
993
  api_client.save_code(worksheet["worksheet_id"], st.session_state.code)
994
- st.success("Template loaded and saved!")
995
  except:
996
- st.success("Template loaded!")
997
  st.rerun()
998
 
999
- # Indentation help
1000
- with st.expander("πŸ“ Indentation Help"):
1001
- if language in ["python", "py"]:
1002
- st.write("""
1003
- **Python Indentation Rules:**
1004
- - Use **4 spaces** per indentation level
1005
- - Consistent indentation is required
1006
- - Common places for indentation:
1007
- - Inside functions: 4 spaces
1008
- - Inside loops (for, while): 4 spaces
1009
- - Inside if/else blocks: 4 spaces
1010
- - Class methods: 8 spaces from class definition
1011
-
1012
- **Example:**
1013
- ```python
1014
- def greet(name): # No indentation
1015
- print(name) # 4 spaces
1016
- if name: # 4 spaces
1017
- print("Hi") # 8 spaces
1018
- ```
1019
- """)
1020
- else:
1021
- st.write("""
1022
- **JavaScript Indentation Rules:**
1023
- - Use **2 spaces** per indentation level
1024
- - Common places for indentation:
1025
- - Inside functions: 2 spaces
1026
- - Inside loops (for, while): 2 spaces
1027
- - Inside if/else blocks: 2 spaces
1028
- - Inside objects: 2 spaces
1029
-
1030
- **Example:**
1031
- ```javascript
1032
- function greet(name) { // No indentation
1033
- console.log(name); // 2 spaces
1034
- if (name) { // 2 spaces
1035
- console.log("Hi"); // 4 spaces
1036
- }
1037
- }
1038
- ```
1039
- """)
1040
 
1041
- # ================================================================
1042
- # CODE EDITOR
1043
- # ================================================================
1044
- st.divider()
1045
- st.subheader("⌨️ Code Editor")
1046
-
1047
- if "code" not in st.session_state:
1048
- st.session_state.code = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1049
 
1050
- # Initialize worksheet
1051
- if "current_worksheet_id" not in st.session_state or st.session_state.get(
1052
- "current_question_id") != question_id:
 
1053
  try:
1054
- worksheet = api_client.get_worksheet(
1055
- st.session_state.room_id,
1056
- st.session_state.student_id,
1057
- question_id
1058
- )
1059
- st.session_state.current_worksheet_id = worksheet["worksheet_id"]
1060
- st.session_state.current_question_id = question_id
1061
- if worksheet.get("code"):
1062
- st.session_state.code = worksheet["code"]
1063
- except Exception as e:
1064
- st.error(f"Error loading worksheet: {e}")
1065
-
1066
- code_input = st.text_area(
1067
- "Write your code here:",
1068
- value=st.session_state.code,
1069
- height=250,
1070
- key="code_input"
1071
- )
1072
 
1073
- # Auto-save
1074
- if code_input != st.session_state.code:
1075
- st.session_state.code = code_input
1076
- if "current_worksheet_id" in st.session_state:
1077
- try:
1078
- api_client.save_code(st.session_state.current_worksheet_id, code_input)
1079
- except:
1080
- pass
1081
 
1082
- # ================================================================
1083
- # CODE QUALITY CHECK
1084
- # ================================================================
1085
- st.divider()
1086
- st.subheader("πŸ“Š Code Quality Check")
1087
 
1088
- if code_input.strip():
1089
- col1, col2, col3 = st.columns(3)
 
 
 
 
 
 
 
1090
 
1091
- has_output = False
1092
- if language in ["python", "py"]:
1093
- has_output = "print(" in code_input
 
 
 
 
 
 
 
 
 
 
 
 
 
1094
  else:
1095
- has_output = "console.log(" in code_input
1096
-
1097
- with col1:
1098
- if has_output:
1099
- st.success(f"βœ… Has Output Statement")
1100
- else:
1101
- st.warning(f"⚠️ No Output Statement")
1102
-
1103
- char_count = len(code_input)
1104
- with col2:
1105
- st.info(f"πŸ“ Characters: {char_count}")
1106
-
1107
- lines = code_input.split('\n')
1108
- with col3:
1109
- st.info(f"πŸ“„ Lines: {len(lines)}")
1110
-
1111
- # ================================================================
1112
- # RUN & SUBMIT BUTTONS
1113
- # ================================================================
1114
- st.divider()
1115
- col_run, col_submit, col_save = st.columns(3)
1116
-
1117
- with col_run:
1118
- if st.button("▢️ Run Code", use_container_width=True):
1119
- if code_input.strip():
1120
- with st.spinner("Executing..."):
1121
- result = api_client.execute_code(code_input, language)
1122
- if "output" in result and result.get("success", True):
1123
- st.success("βœ… Execution successful!")
1124
- st.code(result["output"], language="text")
1125
- elif "error" in result:
1126
- st.error("❌ Execution failed!")
1127
- st.code(result["error"], language="text")
1128
- else:
1129
- st.warning("Write some code first!")
1130
-
1131
- with col_submit:
1132
- if st.button("πŸš€ Submit Solution", use_container_width=True, type="primary"):
1133
- if code_input.strip():
1134
- with st.spinner("Judging your solution against all test cases..."):
1135
- result = api_client.submit_solution(
1136
- code=code_input,
1137
- language=language,
1138
- room_id=st.session_state.room_id,
1139
- question_id=question_id,
1140
- student_id=st.session_state.student_id
1141
- )
1142
-
1143
- # Store result for display
1144
- st.session_state.last_submission = result
1145
- else:
1146
- st.warning("Write some code first!")
1147
-
1148
- with col_save:
1149
- if st.button("πŸ’Ύ Save Code", use_container_width=True):
1150
- if "current_worksheet_id" in st.session_state:
1151
- try:
1152
- api_client.save_code(st.session_state.current_worksheet_id, code_input)
1153
- st.success("βœ… Code saved!")
1154
- except Exception as e:
1155
- st.error(f"Error saving: {e}")
1156
-
1157
- # ================================================================
1158
- # SUBMISSION RESULTS DISPLAY (LeetCode-style)
1159
- # ================================================================
1160
- if "last_submission" in st.session_state and st.session_state.last_submission:
1161
- submission = st.session_state.last_submission
1162
-
1163
- st.markdown("---")
1164
- st.subheader("πŸ“Š Submission Results")
1165
-
1166
- overall = submission.get("overall", "Unknown")
1167
- passed = submission.get("passed_cases", 0)
1168
- total = submission.get("total_cases", 0)
1169
- score = submission.get("score", 0)
1170
- max_score = submission.get("max_score", 100)
1171
-
1172
- # Overall verdict banner with score
1173
- if overall == "Accepted":
1174
- st.success(f"πŸŽ‰ **{overall}** β€” All {total} test case(s) passed! Score: **{score:.0f}/{max_score:.0f}**")
1175
- elif overall == "Wrong Answer":
1176
- st.error(f"❌ **{overall}** β€” {passed}/{total} test case(s) passed. Score: **{score:.0f}/{max_score:.0f}**")
1177
- elif overall == "Runtime Error":
1178
- st.error(f"πŸ’₯ **{overall}** β€” {passed}/{total} test case(s) passed. Score: **{score:.0f}/{max_score:.0f}**")
1179
  else:
1180
- st.warning(f"⚠️ **{overall}** β€” {passed}/{total} test case(s) passed. Score: **{score:.0f}/{max_score:.0f}**")
1181
-
1182
- # Per-case results
1183
- case_results = submission.get("results", [])
1184
- for cr in case_results:
1185
- case_num = cr.get("case_number", "?")
1186
- is_hidden = cr.get("is_hidden", False)
1187
- case_passed = cr.get("passed", False)
1188
- case_status = cr.get("status", "")
1189
-
1190
- icon = "βœ…" if case_passed else "❌"
1191
-
1192
- if is_hidden:
1193
- # Hidden test case β€” only show pass/fail
1194
- st.write(f"{icon} **Hidden Test Case {case_num}**: {case_status}")
1195
- else:
1196
- # Example test case β€” show full details
1197
- with st.expander(f"{icon} Test Case {case_num}: {case_status}", expanded=not case_passed):
1198
- tc_col1, tc_col2, tc_col3 = st.columns(3)
1199
- with tc_col1:
1200
- st.markdown("**Input:**")
1201
- st.code(cr.get("input_data", "(no input)"), language="text")
1202
- with tc_col2:
1203
- st.markdown("**Expected Output:**")
1204
- st.code(cr.get("expected_output", ""), language="text")
1205
- with tc_col3:
1206
- st.markdown("**Your Output:**")
1207
- actual = cr.get("actual_output", "")
1208
- if cr.get("error"):
1209
- st.code(cr.get("error", ""), language="text")
1210
- else:
1211
- st.code(actual if actual else "(no output)", language="text")
1212
 
1213
- else:
1214
- st.info("No questions available yet. Ask your teacher to create some!")
1215
-
1216
- except Exception as e:
1217
- st.error(f"Error: {e}")
 
 
 
1218
 
1219
- else:
1220
- st.info("πŸ“Œ Join a room using the sidebar to get started!")
1221
 
1222
 
1223
  # ============================================================================
 
696
 
697
 
698
  def student_page(api_client):
699
+ """Student workspace β€” LeetCode / HackerRank style split-pane layout"""
 
700
 
701
  # Sidebar for room joining
702
  with st.sidebar:
 
721
  else:
722
  st.error(f"Error: {e}")
723
  except Exception as e:
 
724
  st.error(f"Error: {e}")
725
 
726
+ if "room_id" not in st.session_state:
727
+ st.title("πŸ’» Online Exam IDE")
728
+ st.info("πŸ“Œ Join a room using the sidebar to get started!")
729
+ return
730
+
731
+ # ================================================================
732
+ # ROOM & TIMING CHECKS
733
+ # ================================================================
734
+ try:
735
+ room = api_client.get_room(st.session_state.room_id)
736
+ start_time_str = room.get("start_time")
737
+ end_time_str = room.get("end_time")
738
+
739
+ now = datetime.now()
740
+ start_time = datetime.fromisoformat(start_time_str) if start_time_str else None
741
+ end_time = datetime.fromisoformat(end_time_str) if end_time_str else None
742
+
743
+ if start_time and now < start_time:
744
+ st.warning(f"Exam has not started yet. Start time: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
745
+ st.metric("Time until start", str(start_time - now).split('.')[0])
746
+ if st.button("Refresh Status"):
747
+ st.rerun()
748
+ return
749
+
750
+ if end_time and now > end_time:
751
+ st.error("Exam has ended. You can no longer submit code.")
752
+ st.metric("Exam Ended", end_time.strftime('%Y-%m-%d %H:%M:%S'))
753
+ return
754
+
755
+ except Exception as e:
756
+ st.error(f"Error checking exam status: {e}")
757
+ return
758
+
759
+ # ================================================================
760
+ # BLOCKED STUDENT CHECK
761
+ # ================================================================
762
+ blocked_students = room.get("blocked_students", [])
763
+ student_id = st.session_state.student_id
764
+ my_flags = room.get("student_red_flags", {}).get(student_id, 0)
765
+
766
+ if student_id in blocked_students or my_flags > 3:
767
+ st.markdown("""
768
+ <div style="
769
+ background: linear-gradient(135deg, #b91c1c 0%, #7f1d1d 100%);
770
+ border: 3px solid #ef4444;
771
+ border-radius: 16px;
772
+ padding: 60px 40px;
773
+ text-align: center;
774
+ margin: 40px auto;
775
+ max-width: 700px;
776
+ box-shadow: 0 0 60px rgba(239, 68, 68, 0.4);
777
+ ">
778
+ <div style="font-size: 80px; margin-bottom: 20px;">🚫</div>
779
+ <h1 style="color: #ffffff; font-size: 42px; margin-bottom: 10px; font-weight: 800;">
780
+ EXAM ACCESS BLOCKED
781
+ </h1>
782
+ <p style="color: #fca5a5; font-size: 20px; margin-bottom: 30px;">
783
+ You have been permanently blocked from this exam due to <strong>repeated security violations</strong>.
784
+ </p>
785
+ <div style="
786
+ background: rgba(0,0,0,0.3);
787
+ border-radius: 12px;
788
+ padding: 20px;
789
+ margin: 20px auto;
790
+ max-width: 400px;
791
+ ">
792
+ <p style="color: #f87171; font-size: 28px; font-weight: 700; margin: 0;">
793
+ Your Score: 0 / 100
794
+ </p>
795
+ <p style="color: #fca5a5; font-size: 16px; margin-top: 8px;">
796
+ Violations recorded: """ + str(my_flags) + """
797
+ </p>
798
+ </div>
799
+ <p style="color: #d1d5db; font-size: 14px; margin-top: 20px;">
800
+ This action is final. Contact your teacher if you believe this is an error.
801
+ </p>
802
+ </div>
803
+ """, unsafe_allow_html=True)
804
+ return
805
+
806
+ # ================================================================
807
+ # SECURITY SCRIPT & EXAM HEADER
808
+ # ================================================================
809
+ if end_time:
810
+ time_left = end_time - now
811
+
812
+ st_room_id = st.session_state.room_id
813
+ st_student_id = st.session_state.student_id
814
+
815
+ security_script = f"""
816
+ <script>
817
+ const targetWindow = window.parent;
818
+ const targetDocument = targetWindow.document;
819
+
820
+ let violationCount = {my_flags};
821
+
822
+ function reportViolation() {{
823
+ violationCount++;
824
+ fetch("{PUBLIC_BACKEND_URL}/api/rooms/{st_room_id}/report_violation", {{
825
+ method: "POST",
826
+ headers: {{
827
+ "Content-Type": "application/json"
828
+ }},
829
+ body: JSON.stringify({{
830
+ "student_id": "{st_student_id}"
831
+ }})
832
+ }}).then(r => r.json()).then(data => {{
833
+ if (data.blocked) {{
834
+ showOverlay('<h1 style="font-size: 60px;">🚫 BLOCKED</h1><h2 style="font-size: 30px;">You have been permanently blocked from this exam.</h2><p style="font-size: 22px;">Your score is now 0. Contact your teacher.</p>', true);
835
+ // Disable click-to-dismiss for blocked overlay
836
  var overlay = targetDocument.getElementById('security-overlay');
837
+ if (overlay) overlay.onclick = null;
838
+ // Force reload after a short delay so the server-side block kicks in
839
+ setTimeout(() => {{ targetWindow.location.reload(); }}, 3000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840
  }}
841
+ }}).catch(e => console.error(e));
842
+ }}
843
+
844
+ function requestFullScreen() {{
845
+ var elem = targetDocument.documentElement;
846
+ if (elem.requestFullscreen) {{
847
+ elem.requestFullscreen().catch(err => {{
848
+ console.log("Error attempting to enable full-screen mode: " + err.message);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
849
  }});
850
+ }} else if (elem.webkitRequestFullscreen) {{
851
+ elem.webkitRequestFullscreen();
852
+ }} else if (elem.msRequestFullscreen) {{
853
+ elem.msRequestFullscreen();
854
+ }}
855
+ }}
856
+
857
+ function showOverlay(message, isRed = true) {{
858
+ var overlay = targetDocument.getElementById('security-overlay');
859
+ if (!overlay) {{
860
+ overlay = targetDocument.createElement('div');
861
+ overlay.id = 'security-overlay';
862
+ overlay.style.position = 'fixed';
863
+ overlay.style.top = '0';
864
+ overlay.style.left = '0';
865
+ overlay.style.width = '100vw';
866
+ overlay.style.height = '100vh';
867
+ overlay.style.zIndex = '999999';
868
+ overlay.style.color = 'white';
869
+ overlay.style.display = 'flex';
870
+ overlay.style.justifyContent = 'center';
871
+ overlay.style.alignItems = 'center';
872
+ overlay.style.flexDirection = 'column';
873
+
874
+ overlay.onclick = function() {{
875
+ overlay.style.display = 'none';
876
+ targetDocument.title = "Online Exam IDE";
877
+ requestFullScreen();
878
+ }};
879
+
880
+ targetDocument.body.appendChild(overlay);
881
+ }}
882
+
883
+ overlay.style.backgroundColor = isRed ? 'rgba(255, 0, 0, 0.98)' : 'rgba(0, 0, 0, 0.9)';
884
+ overlay.innerHTML = message;
885
+ overlay.style.display = 'flex';
886
+ }}
887
+
888
+ targetDocument.addEventListener('contextmenu', event => {{
889
+ event.preventDefault();
890
+ event.stopPropagation();
891
+ reportViolation();
892
+ showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">Right-click is forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
893
+ return false;
894
+ }}, true);
895
+
896
+ targetDocument.addEventListener('keydown', function(e) {{
897
+ if (e.ctrlKey || e.altKey || e.metaKey) {{
898
+ e.preventDefault();
899
+ e.stopPropagation();
900
+ reportViolation();
901
+ showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">Keyboard shortcuts are forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
902
+ return false;
903
+ }}
904
+ if (e.keyCode >= 112 && e.keyCode <= 123) {{
905
+ e.preventDefault();
906
+ e.stopPropagation();
907
+ reportViolation();
908
+ showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">Function keys are forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
909
+ return false;
910
+ }}
911
+ }}, true);
912
+
913
+ ['copy', 'cut', 'paste'].forEach(e => {{
914
+ targetDocument.addEventListener(e, function(event) {{
915
+ event.preventDefault();
916
+ event.stopPropagation();
917
+ reportViolation();
918
+ let action = e.toUpperCase();
919
+ showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">' + action + ' is forbidden!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
920
+ return false;
921
+ }}, true);
922
+ }});
923
+
924
+ targetWindow.addEventListener('blur', function() {{
925
+ targetDocument.title = " EXAM WARNING: COME BACK!";
926
+ reportViolation();
927
+ showOverlay('<h1 style="font-size: 50px;"> VIOLATION</h1><h2 style="font-size: 30px;">You left the exam window!</h2><p style="font-size: 20px;">Return and CLICK HERE to resume.</p>');
928
+ }});
929
+
930
+ function handleFullscreenChange() {{
931
+ if (!targetDocument.fullscreenElement && !targetDocument.webkitFullscreenElement && !targetDocument.msFullscreenElement) {{
932
+ reportViolation();
933
+ showOverlay('<h1 style="font-size: 40px;"> FULLSCREEN REQUIRED</h1><h2 style="font-size: 25px;">You cannot leave fullscreen mode.</h2><p style="font-size: 20px;">CLICK HERE to return to fullscreen.</p>', true);
934
+ }}
935
+ }}
936
+
937
+ targetDocument.addEventListener('fullscreenchange', handleFullscreenChange);
938
+ targetDocument.addEventListener('webkitfullscreenchange', handleFullscreenChange);
939
+ targetDocument.addEventListener('mozfullscreenchange', handleFullscreenChange);
940
+ targetDocument.addEventListener('MSFullscreenChange', handleFullscreenChange);
941
+
942
+ const style = targetDocument.createElement('style');
943
+ style.innerHTML = `
944
+ [data-testid="stSidebar"] {{ display: none !important; }}
945
+ [data-testid="stToolbar"] {{ visibility: hidden !important; }}
946
+ header {{ visibility: hidden !important; }}
947
+ `;
948
+ targetDocument.head.appendChild(style);
949
+
950
+ setInterval(function() {{
951
+ if (!targetDocument.fullscreenElement && !targetDocument.webkitFullscreenElement && !targetDocument.msFullscreenElement) {{
952
+ var overlay = targetDocument.getElementById('security-overlay');
953
+ if (!overlay || overlay.style.display == 'none') {{
954
+ showOverlay('<h1 style="font-size: 40px;"> FULLSCREEN REQUIRED</h1><h2 style="font-size: 25px;">You cannot leave fullscreen mode.</h2><p style="font-size: 20px;">CLICK HERE to return to fullscreen.</p>', true);
955
+ }}
956
+ }}
957
+ }}, 1000);
958
+
959
+ setTimeout(requestFullScreen, 500);
960
+ console.log("Security script loaded and attached to parent");
961
+ </script>
962
+ """
963
+ components.html(security_script, height=0, width=0)
964
 
965
+ # ================================================================
966
+ # TOP BAR: Timer + Violations + Fullscreen
967
+ # ================================================================
968
+ top_col1, top_col2, top_col3, top_col4 = st.columns([2, 1, 1, 1])
969
+ with top_col1:
970
+ st.markdown(f"**πŸ’» {st.session_state.student_name}** β€” *{room.get('room_name', 'Exam')}*")
971
+ with top_col2:
972
+ st.metric("⏱ Time Left", str(time_left).split('.')[0])
973
+ with top_col3:
974
+ violation_color = "πŸ”΄" if my_flags > 0 else "🟒"
975
+ st.metric(f"{violation_color} Violations", f"{my_flags} / 3")
976
+ with top_col4:
977
+ st.markdown("""
978
+ <button onclick="parent.document.documentElement.requestFullscreen()" style="
979
+ background-color: #FF4B4B;
980
+ color: white;
981
+ padding: 8px 16px;
982
+ border: none;
983
+ border-radius: 5px;
984
+ cursor: pointer;
985
+ font-weight: bold;
986
+ font-size: 13px;">
987
+ πŸ–₯️ Fullscreen
988
+ </button>
989
+ """, unsafe_allow_html=True)
990
+
991
+ if st.button("πŸ”„ Refresh", key="refresh_timer"):
992
+ st.rerun()
993
 
994
+ # ================================================================
995
+ # QUESTION + SPLIT-PANE IDE LAYOUT
996
+ # ================================================================
997
+ try:
998
+ questions = api_client.get_questions(st.session_state.room_id)
999
+ question_list = questions.get("questions", [])
1000
 
1001
+ if not question_list:
1002
+ st.info("No questions available yet. Ask your teacher to create some!")
1003
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1004
 
1005
+ # Question tab selector (like LeetCode problem tabs)
1006
+ question_names = [f"Q{i+1}: {q.get('question_text', 'Question')[:50]}..." for i, q in enumerate(question_list)]
1007
+ selected_q_idx = st.selectbox("πŸ“‹ Select Problem", range(len(question_names)),
1008
+ format_func=lambda i: question_names[i], label_visibility="collapsed")
1009
+ selected_question = question_list[selected_q_idx]
1010
+ question_id = selected_question.get("question_id")
1011
+ language = selected_question.get("language", "Python").lower()
1012
+
1013
+ st.markdown("---")
1014
 
1015
  # ================================================================
1016
+ # SPLIT PANE: LEFT (Problem) | RIGHT (Code Editor)
1017
  # ================================================================
1018
+ left_col, right_col = st.columns([1, 1], gap="medium")
1019
+
1020
+ # ========================
1021
+ # LEFT PANEL: Problem
1022
+ # ========================
1023
+ with left_col:
1024
+ st.markdown("### πŸ“ Problem Statement")
1025
+ st.markdown(f"""
1026
+ <div style="
1027
+ background: rgba(30, 36, 46, 0.6);
1028
+ border: 1px solid rgba(255,255,255,0.1);
1029
+ border-radius: 10px;
1030
+ padding: 20px;
1031
+ margin-bottom: 16px;
1032
+ line-height: 1.7;
1033
+ ">
1034
+ {selected_question['question_text']}
1035
+ </div>
1036
+ """, unsafe_allow_html=True)
1037
+
1038
+ # Example Test Cases
1039
+ example_test_cases = selected_question.get("test_cases", [])
1040
+ hidden_count = selected_question.get("hidden_test_cases_count", 0)
1041
+
1042
+ if example_test_cases or hidden_count > 0:
1043
+ st.markdown("### πŸ§ͺ Test Cases")
1044
+
1045
+ if example_test_cases:
1046
+ for j, tc in enumerate(example_test_cases):
1047
+ st.markdown(f"**Example {j+1}:**")
1048
+ tc_left, tc_right = st.columns(2)
1049
+ with tc_left:
1050
+ input_display = tc.get("input_data", "(no input)")
1051
+ st.code(input_display if input_display else "(no input)", language="text")
1052
+ with tc_right:
1053
+ st.code(tc.get("expected_output", ""), language="text")
1054
+
1055
+ if hidden_count > 0:
1056
+ st.info(f"πŸ”’ **{hidden_count}** hidden test case(s) will be used for final judging.")
1057
+
1058
+ # ================================================================
1059
+ # SUBMISSION RESULTS (shown in left panel, like LeetCode)
1060
+ # ================================================================
1061
+ if "last_submission" in st.session_state and st.session_state.last_submission:
1062
+ submission = st.session_state.last_submission
1063
+
1064
  st.markdown("---")
1065
+ st.markdown("### πŸ“Š Submission Results")
1066
+
1067
+ overall = submission.get("overall", "Unknown")
1068
+ passed = submission.get("passed_cases", 0)
1069
+ total = submission.get("total_cases", 0)
1070
+ score = submission.get("score", 0)
1071
+ max_score = submission.get("max_score", 100)
1072
+
1073
+ # Verdict banner
1074
+ if overall == "Accepted":
1075
+ st.success(f"πŸŽ‰ **{overall}** β€” All {total} test case(s) passed! Score: **{score:.0f}/{max_score:.0f}**")
1076
+ elif overall == "Wrong Answer":
1077
+ st.error(f"❌ **{overall}** β€” {passed}/{total} passed. Score: **{score:.0f}/{max_score:.0f}**")
1078
+ elif overall == "Runtime Error":
1079
+ st.error(f"πŸ’₯ **{overall}** β€” {passed}/{total} passed. Score: **{score:.0f}/{max_score:.0f}**")
1080
+ else:
1081
+ st.warning(f"⚠️ **{overall}** β€” {passed}/{total} passed. Score: **{score:.0f}/{max_score:.0f}**")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1082
 
1083
+ # Per-case results
1084
+ case_results = submission.get("results", [])
1085
+ for cr in case_results:
1086
+ case_num = cr.get("case_number", "?")
1087
+ is_hidden = cr.get("is_hidden", False)
1088
+ case_passed = cr.get("passed", False)
1089
+ case_status = cr.get("status", "")
1090
 
1091
+ icon = "βœ…" if case_passed else "❌"
1092
+
1093
+ if is_hidden:
1094
+ st.write(f"{icon} **Hidden Test Case {case_num}**: {case_status}")
1095
+ else:
1096
+ with st.expander(f"{icon} Test Case {case_num}: {case_status}", expanded=not case_passed):
1097
+ tc_col1, tc_col2, tc_col3 = st.columns(3)
1098
+ with tc_col1:
1099
+ st.markdown("**Input:**")
1100
+ st.code(cr.get("input_data", "(no input)"), language="text")
1101
+ with tc_col2:
1102
+ st.markdown("**Expected:**")
1103
+ st.code(cr.get("expected_output", ""), language="text")
1104
+ with tc_col3:
1105
+ st.markdown("**Your Output:**")
1106
+ actual = cr.get("actual_output", "")
1107
+ if cr.get("error"):
1108
+ st.code(cr.get("error", ""), language="text")
1109
+ else:
1110
+ st.code(actual if actual else "(no output)", language="text")
1111
+
1112
+ # ========================
1113
+ # RIGHT PANEL: Code Editor
1114
+ # ========================
1115
+ with right_col:
1116
+ # Language badge
1117
+ lang_icons = {"python": "🐍", "javascript": "🟨", "java": "β˜•", "c++": "βš™οΈ"}
1118
+ lang_icon = lang_icons.get(language, "πŸ“„")
1119
+ st.markdown(f"### {lang_icon} Code Editor β€” `{language.upper()}`")
1120
+
1121
+ # Template selector
1122
+ with st.expander("πŸ“‹ Templates & Help", expanded=False):
1123
  if language in ["python", "py"]:
1124
  templates = PYTHON_TEMPLATES
1125
  else:
 
1136
  question_id
1137
  )
1138
  api_client.save_code(worksheet["worksheet_id"], st.session_state.code)
 
1139
  except:
1140
+ pass
1141
  st.rerun()
1142
 
1143
+ # Initialize code
1144
+ if "code" not in st.session_state:
1145
+ st.session_state.code = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1146
 
1147
+ # Initialize worksheet
1148
+ if "current_worksheet_id" not in st.session_state or st.session_state.get(
1149
+ "current_question_id") != question_id:
1150
+ try:
1151
+ worksheet = api_client.get_worksheet(
1152
+ st.session_state.room_id,
1153
+ st.session_state.student_id,
1154
+ question_id
1155
+ )
1156
+ st.session_state.current_worksheet_id = worksheet["worksheet_id"]
1157
+ st.session_state.current_question_id = question_id
1158
+ if worksheet.get("code"):
1159
+ st.session_state.code = worksheet["code"]
1160
+ except Exception as e:
1161
+ st.error(f"Error loading worksheet: {e}")
1162
+
1163
+ # Code editor
1164
+ code_input = st.text_area(
1165
+ "Write your code here:",
1166
+ value=st.session_state.code,
1167
+ height=350,
1168
+ key="code_input",
1169
+ label_visibility="collapsed"
1170
+ )
1171
 
1172
+ # Auto-save
1173
+ if code_input != st.session_state.code:
1174
+ st.session_state.code = code_input
1175
+ if "current_worksheet_id" in st.session_state:
1176
  try:
1177
+ api_client.save_code(st.session_state.current_worksheet_id, code_input)
1178
+ except:
1179
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1180
 
1181
+ # Code quality indicators
1182
+ if code_input.strip():
1183
+ q_col1, q_col2, q_col3 = st.columns(3)
 
 
 
 
 
1184
 
1185
+ has_output = False
1186
+ if language in ["python", "py"]:
1187
+ has_output = "print(" in code_input
1188
+ else:
1189
+ has_output = "console.log(" in code_input
1190
 
1191
+ with q_col1:
1192
+ if has_output:
1193
+ st.success("βœ… Output")
1194
+ else:
1195
+ st.warning("⚠️ No Output")
1196
+ with q_col2:
1197
+ st.info(f"πŸ“ {len(code_input)} chars")
1198
+ with q_col3:
1199
+ st.info(f"πŸ“„ {len(code_input.splitlines())} lines")
1200
 
1201
+ # ================================================================
1202
+ # ACTION BUTTONS: Run | Submit | Save
1203
+ # ================================================================
1204
+ btn_col1, btn_col2, btn_col3 = st.columns(3)
1205
+
1206
+ with btn_col1:
1207
+ if st.button("▢️ Run Code", use_container_width=True):
1208
+ if code_input.strip():
1209
+ with st.spinner("Executing..."):
1210
+ result = api_client.execute_code(code_input, language)
1211
+ if "output" in result and result.get("success", True):
1212
+ st.success("βœ… Execution successful!")
1213
+ st.code(result["output"], language="text")
1214
+ elif "error" in result:
1215
+ st.error("❌ Execution failed!")
1216
+ st.code(result["error"], language="text")
1217
  else:
1218
+ st.warning("Write some code first!")
1219
+
1220
+ with btn_col2:
1221
+ if st.button("πŸš€ Submit", use_container_width=True, type="primary"):
1222
+ if code_input.strip():
1223
+ with st.spinner("Judging against all test cases..."):
1224
+ result = api_client.submit_solution(
1225
+ code=code_input,
1226
+ language=language,
1227
+ room_id=st.session_state.room_id,
1228
+ question_id=question_id,
1229
+ student_id=st.session_state.student_id
1230
+ )
1231
+ st.session_state.last_submission = result
1232
+ st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1233
  else:
1234
+ st.warning("Write some code first!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1235
 
1236
+ with btn_col3:
1237
+ if st.button("πŸ’Ύ Save", use_container_width=True):
1238
+ if "current_worksheet_id" in st.session_state:
1239
+ try:
1240
+ api_client.save_code(st.session_state.current_worksheet_id, code_input)
1241
+ st.success("βœ… Saved!")
1242
+ except Exception as e:
1243
+ st.error(f"Error: {e}")
1244
 
1245
+ except Exception as e:
1246
+ st.error(f"Error: {e}")
1247
 
1248
 
1249
  # ============================================================================