import streamlit as st import streamlit.components.v1 as components import requests import json import os from datetime import datetime import time # ============================================================================ # STEP 4: CODE TEMPLATES CONFIGURATION # ============================================================================ # Python Templates (8 templates) PYTHON_TEMPLATES = { "Simple Function": '''def greet(name): """A simple greeting function""" print(f"Hello, {name}!") greet("World")''', " Function with Math": '''def add_numbers(a, b): """Add two numbers and return result""" result = a + b print(f"{a} + {b} = {result}") return result add_numbers(5, 10)''', " For Loop": '''fruits = ["apple", "banana", "orange"] for fruit in fruits: print(f"I like {fruit}")''', " If-Else": '''age = 20 if age >= 18: print("You are an adult") else: print("You are a minor")''', " List Operations": '''numbers = [1, 2, 3, 4, 5] # Add element numbers.append(6) # Remove element numbers.remove(3) # Print all for num in numbers: print(num)''', " While Loop": '''count = 0 while count < 5: print(f"Count: {count}") count += 1''', " List Comprehension": '''# Create a list of squares squares = [x**2 for x in range(5)] print(squares) # Filter even numbers numbers = [x for x in range(10) if x % 2 == 0] print(numbers)''', "Dictionary": '''student = { "name": "John", "age": 20, "grade": "A" } print(student["name"]) print(student["grade"])''' } # JavaScript Templates (5 templates) JAVASCRIPT_TEMPLATES = { " Simple Function": '''function greet(name) { console.log(`Hello, ${name}!`); } greet("World");''', " Function with Math": '''function addNumbers(a, b) { let result = a + b; console.log(`${a} + ${b} = ${result}`); return result; } addNumbers(5, 10);''', " For Loop": '''let fruits = ["apple", "banana", "orange"]; for (let i = 0; i < fruits.length; i++) { console.log(`I like ${fruits[i]}`); }''', " If-Else": '''let age = 20; if (age >= 18) { console.log("You are an adult"); } else { console.log("You are a minor"); }''', " Array Operations": '''let numbers = [1, 2, 3, 4, 5]; // Add element numbers.push(6); // Remove element numbers.splice(2, 1); // Print all for (let num of numbers) { console.log(num); }''' } # ============================================================================ # CONFIGURATION # ============================================================================ # The URL used by Streamlit (server) to contact FastAPI (server) BACKEND_URL = os.getenv("BACKEND_URL", "http://127.0.0.1:8000") # The URL used by the browser (client JS) to contact the unified Nginx proxy PUBLIC_BACKEND_URL = os.getenv("PUBLIC_BACKEND_URL", "") # ============================================================================ # API CLIENT # ============================================================================ class APIClient: def __init__(self, base_url): self.base_url = base_url self.session_id = None self.role = None def create_room(self, room_name: str, teacher_name: str, language: str = "Python", duration: int = 30, start_time: str = None): """Create a new exam room""" payload = { "room_name": room_name, "teacher_name": teacher_name, "language": language, "duration": duration, "session_id": self.session_id } if start_time: payload["start_time"] = start_time response = requests.post( f"{self.base_url}/api/rooms/create", json=payload ) return response.json() def join_room(self, room_code: str, student_name: str): """Join an existing exam room""" response = requests.post( f"{self.base_url}/api/rooms/{room_code}/join", json={ "student_name": student_name, "session_id": self.session_id } ) return response.json() def get_room(self, room_id: str): """Get room details""" response = requests.get(f"{self.base_url}/api/rooms/{room_id}") return response.json() def create_question(self, room_id: str, question_text: str, language: str, test_cases: list = None): """Create a question in the room with optional test cases""" payload = { "question_text": question_text, "language": language, } if test_cases: payload["test_cases"] = test_cases response = requests.post( f"{self.base_url}/api/rooms/{room_id}/questions", json=payload ) return response.json() def get_questions(self, room_id: str): """Get all questions in a room (hidden test cases filtered out)""" response = requests.get(f"{self.base_url}/api/rooms/{room_id}/questions") return response.json() def get_questions_full(self, room_id: str): """Get all questions including hidden test cases (teacher use)""" response = requests.get(f"{self.base_url}/api/rooms/{room_id}/questions/full") return response.json() def get_worksheet(self, room_id: str, student_id: str, question_id: str): """Get student's worksheet""" response = requests.get( f"{self.base_url}/api/worksheets/{room_id}/{student_id}/{question_id}" ) return response.json() def save_code(self, worksheet_id: str, code: str): """Save student code""" response = requests.post( f"{self.base_url}/api/worksheets/{worksheet_id}/save", json={"code": code} ) return response.json() def execute_code(self, code: str, language: str): """Execute code and get output""" response = requests.post( f"{self.base_url}/api/execute", json={ "code": code, "language": language } ) return response.json() def submit_solution(self, code: str, language: str, room_id: str, question_id: str, student_id: str): """Submit solution for auto-judging against all test cases""" response = requests.post( f"{self.base_url}/api/submit", json={ "code": code, "language": language, "room_id": room_id, "question_id": question_id, "student_id": student_id } ) return response.json() def get_student_codes(self, room_id: str): """Get all student codes with NAMES in the room (Live Monitor)""" response = requests.get(f"{self.base_url}/api/rooms/{room_id}/student-codes") return response.json() def get_scores(self, room_id: str): """Get aggregated scores for all students""" response = requests.get(f"{self.base_url}/api/rooms/{room_id}/scores") return response.json() def download_report(self, room_id: str): """Download PDF exam report. Returns raw bytes.""" response = requests.get(f"{self.base_url}/api/rooms/{room_id}/report") if response.status_code == 200: return response.content return None def report_violation(self, room_id: str, student_id: str): """Report a security violation""" try: requests.post( f"{self.base_url}/api/rooms/{room_id}/report_violation", json={"student_id": student_id} ) except: pass def start_exam(self, room_id: str, start_time: str): """Manually start an exam room""" response = requests.post( f"{self.base_url}/api/rooms/{room_id}/start", json={"start_time": start_time} ) return response.json() # ============================================================================ # PAGE FUNCTIONS # ============================================================================ def teacher_page(api_client): """Teacher dashboard""" st.title("๐ Teacher Dashboard") # Sidebar for room creation with st.sidebar: st.header("Create Exam Room") room_name = st.text_input("Exam/Assignment Name") teacher_name = st.text_input("Your Name") language = st.selectbox("Programming Language", ["Python", "JavaScript", "Java", "C++"]) # Duration duration = st.slider("Duration (minutes)", 5, 180, 60, step=5) # Do not set start time initially start_time_iso = None if st.button("Create Exam Room", key="create_room"): if room_name and teacher_name: result = api_client.create_room(room_name, teacher_name, language, duration, start_time_iso) if "room_id" in result: st.session_state.room_id = result["room_id"] st.session_state.room_code = result["room_code"] st.success(f"Room created! Code: {result['room_code']}") else: st.error(f"Error: {result.get('detail', 'Unknown error')}") # Display current room if "room_id" in st.session_state: col1, col2 = st.columns(2) with col1: st.info(f"๐ Room Code: `{st.session_state.room_code}`") with col2: st.info(f"๐ Room ID: `{st.session_state.room_id}`") # ================================================================ # CREATE QUESTION WITH TEST CASES # ================================================================ with st.expander("๐ Create New Question", expanded=True): question_text = st.text_area("Question Text", height=100, placeholder="Write your coding question here...\ne.g., Write a function that reads two integers from stdin and prints their sum.") question_lang = st.selectbox("Language", ["Python", "JavaScript", "Java", "C++"], key="q_lang") st.divider() st.subheader("๐งช Test Cases") st.caption("Add example test cases (visible to students) and hidden test cases (used for judging only).") # Dynamic test case management using session state if "test_cases_draft" not in st.session_state: st.session_state.test_cases_draft = [] # Show existing draft test cases cases_to_remove = [] for idx, tc in enumerate(st.session_state.test_cases_draft): with st.container(): tc_col1, tc_col2, tc_col3 = st.columns([3, 3, 1]) with tc_col1: tc["input_data"] = st.text_area( f"Input (Test Case {idx + 1})", value=tc.get("input_data", ""), key=f"tc_input_{idx}", height=80, placeholder="e.g., 5 10" ) with tc_col2: tc["expected_output"] = st.text_area( f"Expected Output (Test Case {idx + 1})", value=tc.get("expected_output", ""), key=f"tc_output_{idx}", height=80, placeholder="e.g., 15" ) with tc_col3: tc["is_hidden"] = st.checkbox( "Hidden?", value=tc.get("is_hidden", False), key=f"tc_hidden_{idx}", help="Hidden test cases are NOT shown to students" ) if st.button("๐๏ธ", key=f"tc_remove_{idx}"): cases_to_remove.append(idx) # Visual indicator badge = "๐ Hidden" if tc.get("is_hidden") else "๐๏ธ Visible" st.caption(f"Test Case {idx + 1} โ {badge}") st.divider() # Remove marked test cases if cases_to_remove: for idx in sorted(cases_to_remove, reverse=True): st.session_state.test_cases_draft.pop(idx) st.rerun() # Add new test case button col_add1, col_add2 = st.columns(2) with col_add1: if st.button("โ Add Example Test Case", key="add_example_tc"): st.session_state.test_cases_draft.append({ "input_data": "", "expected_output": "", "is_hidden": False }) st.rerun() with col_add2: if st.button("โ Add Hidden Test Case", key="add_hidden_tc"): st.session_state.test_cases_draft.append({ "input_data": "", "expected_output": "", "is_hidden": True }) st.rerun() # Summary example_count = sum(1 for tc in st.session_state.test_cases_draft if not tc.get("is_hidden")) hidden_count = sum(1 for tc in st.session_state.test_cases_draft if tc.get("is_hidden")) st.info(f"๐ **{example_count}** example test case(s) | **{hidden_count}** hidden test case(s)") # Submit question if st.button("โ Add Question", key="add_question"): if question_text: # Validate test cases valid_test_cases = [ tc for tc in st.session_state.test_cases_draft if tc.get("expected_output", "").strip() # at least expected output must exist ] result = api_client.create_question( st.session_state.room_id, question_text, question_lang, test_cases=valid_test_cases if valid_test_cases else None ) if "question_id" in result: st.success(f"โ Question created with {len(valid_test_cases)} test case(s)!") st.session_state.test_cases_draft = [] # Reset draft st.rerun() else: st.error(f"Error: {result.get('detail', 'Unknown error')}") else: st.warning("Please enter a question text!") # ================================================================ # ROOM OVERVIEW # ================================================================ try: room = api_client.get_room(st.session_state.room_id) room_status = room.get("status", "active") if not room.get("start_time"): st.markdown("---") st.markdown("## ๐ Exam Control Panel") st.info("The exam has not been started yet. Students joining now will wait in a lobby.") panel_col1, panel_col2 = st.columns(2) with panel_col1: st.markdown("#### โก๏ธ Start Immediately") st.caption("Starts the timer now. Latecomers will have a strict **5-minute window** to join before the room is permanently locked.") if st.button("โถ๏ธ Start Exam Now", type="primary", use_container_width=True): # Use UTC for consistency or local datetime start_time_iso = datetime.now().isoformat() result = api_client.start_exam(st.session_state.room_id, start_time_iso) if "success" in result: st.success("โ Exam Started!") st.rerun() with panel_col2: st.markdown("#### ๐ Schedule for Later") with st.expander("Set automated start time"): exam_date = st.date_input("Date", min_value=datetime.now().date(), key="sch_date") exam_time = st.time_input("Time", value=datetime.now().time(), key="sch_time") if st.button("โฐ Schedule Exam", use_container_width=True): start_dt = datetime.combine(exam_date, exam_time) result = api_client.start_exam(st.session_state.room_id, start_dt.isoformat()) if "success" in result: st.success(f"โ Scheduled!") st.rerun() st.markdown("---") col1, col2, col3 = st.columns(3) with col1: st.metric("Connected Students", len(room.get("students", []))) with col2: st.metric("Questions", len(room.get("questions", []))) with col3: if room_status == "expired": st.metric("Status", "๐ด Expired") else: st.metric("Status", "โ Active") # Expired room banner if room_status == "expired": st.warning("โฐ **This exam has ended.** Room code is revoked โ no new students can join or submit.") # Questions list with test case details if room.get("questions"): st.subheader("๐ Questions") for i, q in enumerate(room["questions"]): tc_list = q.get("test_cases", []) example_tc = [tc for tc in tc_list if not tc.get("is_hidden")] hidden_tc = [tc for tc in tc_list if tc.get("is_hidden")] with st.expander(f"Q{i+1}: {q.get('question_text', 'N/A')[:80]}..."): st.write(f"**{q.get('question_text', 'N/A')}**") st.write(f"Language: `{q.get('language', 'Python')}`") st.write(f"Test Cases: **{len(example_tc)}** example, **{len(hidden_tc)}** hidden") if example_tc: st.write("**๐๏ธ Example Test Cases:**") for j, tc in enumerate(example_tc): st.markdown(f"**Case {j+1}:** Input: `{tc.get('input_data', '')}` โ Expected: `{tc.get('expected_output', '')}`") if hidden_tc: st.write("**๐ Hidden Test Cases:**") for j, tc in enumerate(hidden_tc): st.markdown(f"**Case {j+1}:** Input: `{tc.get('input_data', '')}` โ Expected: `{tc.get('expected_output', '')}`") # ================================================================ # SCORES & REPORT SECTION # ================================================================ st.divider() st.subheader("๐ Student Scores") try: scores_response = api_client.get_scores(st.session_state.room_id) scores_list = scores_response.get("scores", []) if scores_list: # Build scoreboard table q_list = room.get("questions", []) scoreboard_data = [] for rank, s in enumerate(scores_list, 1): row = { "Rank": rank, "Student": s.get("student_name", "Unknown"), } for qi, qs in enumerate(s.get("questions", [])): score = qs.get("score", 0) max_s = qs.get("max_score", 100) status = qs.get("status", "not_attempted") icon = "โ " if status == "accepted" else ("๐" if status == "attempted" else "โ") row[f"Q{qi+1}"] = f"{icon} {score:.0f}/{max_s:.0f}" total = s.get("total_score", 0) max_total = s.get("max_total", 0) pct = (total / max_total * 100) if max_total > 0 else 0 row["Total"] = f"{total:.0f}/{max_total:.0f}" row["Percentage"] = f"{pct:.1f}%" row["Violations"] = f"๐ฉ {s.get('red_flags', 0)}" if s.get('red_flags', 0) > 0 else "โ 0" scoreboard_data.append(row) st.dataframe(scoreboard_data, use_container_width=True, hide_index=True) else: st.info("No submissions yet.") except Exception as e: st.error(f"Error loading scores: {e}") # Download report button st.divider() st.subheader("๐ Generate PDF Report") st.caption("Download a comprehensive PDF report with scores, violations, and exam statistics.") if st.button("๐ฅ Download Exam Report (PDF)", key="download_report", use_container_width=True): with st.spinner("Generating PDF report..."): pdf_bytes = api_client.download_report(st.session_state.room_id) if pdf_bytes: st.download_button( label="๐พ Save Report", data=pdf_bytes, file_name=f"exam_report_{room.get('room_name', 'report').replace(' ', '_')}.pdf", mime="application/pdf", key="save_report_btn" ) st.success("โ Report generated! Click 'Save Report' above to download.") else: st.error("Failed to generate report.") except Exception as e: st.error(f"Error loading room: {e}") # ==================================================================== # LIVE CODE MONITOR # ==================================================================== st.divider() st.subheader("๐๏ธ Live Student Monitor") col1, col2, col3 = st.columns([2, 1, 1]) with col1: st.subheader("๐บ Live Code Monitor") # CLASSROOM STATUS TABLE try: detailed_data = api_client.get_student_codes(st.session_state.room_id) student_codes_map = detailed_data.get("student_codes", {}) student_ids_list = room.get("students", []) if student_ids_list: status_data = [] for sid in student_ids_list: s_info = student_codes_map.get(sid, {}) nm = room.get("student_names", {}).get(sid, "Unknown") flgs = s_info.get("red_flags", 0) sts = s_info.get("status", "idle") last_up = s_info.get("last_updated", "") if last_up: last_up = last_up.split("T")[1][:8] status_icon = "๐ฉ" if sts == "working" else ("โ " if sts == "accepted" else "๐ด") flag_icon = "๐ฉ" if flgs > 0 else "โ " status_data.append({ "Student Name": nm, "Status": f"{status_icon} {sts}", "Violations": f"{flag_icon} {flgs}", "Last Active": last_up, "ID": sid }) st.info("**Classroom Overview**") st.dataframe( status_data, column_config={ "Student Name": st.column_config.TextColumn("Student Name", width="medium"), "Status": st.column_config.TextColumn("Status", width="small"), "Violations": st.column_config.TextColumn("Violations (Red Flags)", width="small"), "Last Active": st.column_config.TextColumn("Last Active", width="small"), "ID": st.column_config.TextColumn("Student ID", width="small") }, use_container_width=True, hide_index=True ) else: st.warning("Waiting for students to join...") except Exception as ex: st.error(f"Error loading classroom status: {ex}") col1, col2, col3 = st.columns([2, 1, 1]) with col1: # Get student names from room room = api_client.get_room(st.session_state.room_id) student_names_map = room.get("student_names", {}) student_ids = room.get("students", []) student_display = [] try: detailed_data = api_client.get_student_codes(st.session_state.room_id) student_codes_map = detailed_data.get("student_codes", {}) except: student_codes_map = {} for sid in student_ids: name = student_names_map.get(sid, f"Student ({sid[:8]}...)") s_data = student_codes_map.get(sid, {}) flags = s_data.get("red_flags", 0) flag_str = f" ({flags})" if flags > 0 else "" display_name = f"{name}{flag_str}" student_display.append({"id": sid, "name": display_name}) if student_display: selected_idx = st.selectbox( "Select Student to Monitor", range(len(student_display)), format_func=lambda i: student_display[i]["name"], key="monitor_student" ) selected_student_id = student_display[selected_idx]["id"] selected_student_name = student_display[selected_idx]["name"] else: st.info("No students connected yet") selected_student_id = None selected_student_name = None with col2: auto_refresh = st.checkbox("โ๏ธ Auto Refresh", value=True, key="auto_refresh") with col3: refresh_interval = st.slider("Interval (sec)", 1, 10, 2, key="refresh_interval") # Live code display area if selected_student_id: st.write(f"**Monitoring:** {selected_student_name}") code_placeholder = st.empty() status_placeholder = st.empty() while auto_refresh: try: student_codes_response = api_client.get_student_codes(st.session_state.room_id) if student_codes_response and "student_codes" in student_codes_response: student_data = student_codes_response["student_codes"].get(selected_student_id, {}) code = student_data.get("code", "") student_name = student_data.get("student_name", "Unknown") language = student_data.get("language", "python").lower() status = student_data.get("status", "idle") last_updated = student_data.get("last_updated", "") red_flags = student_data.get("red_flags", 0) with code_placeholder.container(): if red_flags > 0: st.error( f"๐ด **VIOLATION ALERT**: This student has left the exam window {red_flags} times!") if code.strip(): st.code(code, language=language) else: st.info("โ Waiting for student to start coding...") with status_placeholder.container(): col1, col2, col3 = st.columns(3) if status == "idle": status_icon = "" elif status == "working": status_icon = "๐ฉ" elif status == "accepted": status_icon = "โ " else: status_icon = "๐ด" with col1: st.write(f"**Status:** {status_icon} {status.upper()}") with col2: st.write(f"**Language:** {language.upper()}") if last_updated: time_str = last_updated.split('T')[1][:8] if 'T' in last_updated else last_updated with col3: st.write(f"**Updated:** {time_str}") time.sleep(refresh_interval) st.rerun() except Exception as e: st.error(f"Error fetching code: {e}") break else: st.info("๐ Create a room using the sidebar to get started!") def student_page(api_client): """Student workspace โ LeetCode / HackerRank style split-pane layout""" # Sidebar for room joining with st.sidebar: st.header("Join Exam Room") room_code = st.text_input("Room Code") student_name = st.text_input("Your Name") if st.button("Join Room", key="join_room"): if room_code and student_name: try: result = api_client.join_room(room_code, student_name) if "room_id" in result: st.session_state.room_id = result["room_id"] st.session_state.student_id = result["student_id"] st.session_state.student_name = student_name st.success("Room joined!") else: st.error(f"Error: {result.get('detail', 'Unknown error')}") except requests.exceptions.HTTPError as e: if e.response and e.response.status_code == 403: st.error("๐ด This exam has ended. The room code is no longer valid.") else: st.error(f"Error: {e}") except Exception as e: st.error(f"Error: {e}") if "room_id" not in st.session_state: st.title("๐ป Online Exam IDE") st.info("๐ Join a room using the sidebar to get started!") return # ================================================================ # ROOM & TIMING CHECKS # ================================================================ try: room = api_client.get_room(st.session_state.room_id) start_time_str = room.get("start_time") end_time_str = room.get("end_time") now = datetime.now() start_time = datetime.fromisoformat(start_time_str) if start_time_str else None end_time = datetime.fromisoformat(end_time_str) if end_time_str else None if not start_time: st.title("๐ Waiting Lobby") st.info("The teacher has not started this exam yet. Please wait here.") if st.button("๐ Check Status"): st.rerun() return if start_time and now < start_time: st.warning(f"Exam has not started yet. Start time: {start_time.strftime('%Y-%m-%d %H:%M:%S')}") st.metric("Time until start", str(start_time - now).split('.')[0]) if st.button("Refresh Status"): st.rerun() return if end_time and now > end_time: st.error("Exam has ended. You can no longer submit code.") st.metric("Exam Ended", end_time.strftime('%Y-%m-%d %H:%M:%S')) return except Exception as e: st.error(f"Error checking exam status: {e}") return # ================================================================ # BLOCKED STUDENT CHECK # ================================================================ blocked_students = room.get("blocked_students", []) student_id = st.session_state.student_id my_flags = room.get("student_red_flags", {}).get(student_id, 0) if student_id in blocked_students or my_flags > 3: st.markdown("""
You have been permanently blocked from this exam due to repeated security violations.
Your Score: 0 / 100
Violations recorded: """ + str(my_flags) + """
This action is final. Contact your teacher if you believe this is an error.