DigitalTransG2 commited on
Commit
b273087
·
verified ·
1 Parent(s): 75d3f2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -90
app.py CHANGED
@@ -2,55 +2,77 @@ import streamlit as st
2
  import requests
3
  import pandas as pd
4
 
5
- # ==========================
6
  # Firebase config từ secrets.toml
7
- # ==========================
8
  FIREBASE_URL = st.secrets["firebase_database_url"]
9
  FIREBASE_AUTH = st.secrets["firebase_api_key"]
10
 
11
- # ==========================
12
- # Session state
13
- # ==========================
14
- if "creator_logged_in" not in st.session_state:
15
- st.session_state.creator_logged_in = False
16
 
17
- st.title("SmartEdu System")
 
 
 
 
 
 
 
 
 
18
 
19
- # ==========================
20
- # Role Selection
21
- # ==========================
22
- role = st.selectbox("Chọn vai trò", ["Quiz Creator", "Student Evaluation"])
23
 
24
- # ==========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # QUIZ CREATOR
26
- # ==========================
27
- if role == "Quiz Creator":
28
- st.subheader("Đăng nhập Quiz Creator")
29
-
30
- if not st.session_state.creator_logged_in:
31
- username = st.text_input("Tài khoản")
32
- password = st.text_input("Mật khẩu", type="password")
33
-
34
- if st.button("Đăng nhập"):
35
- if username == "master" and password == "master":
36
- st.session_state.creator_logged_in = True
37
- st.success("Đăng nhập thành công!")
38
- st.stop()
 
 
 
 
 
39
  else:
40
- st.error("Sai tài khoản hoặc mật khẩu")
 
41
  st.stop()
42
 
43
- st.success("Bạn đang đăng nhập với quyền Quiz Creator")
44
- st.subheader("Tạo Quiz mới")
 
45
 
46
- quiz_name = st.text_input("Tên Quiz (ví dụ: Quiz1)")
47
 
48
- # ==========================
49
- # 10 CÂU HỎI — ĐÁP ÁN ĐÚNG THEO TEXT
50
- # ==========================
51
  questions = []
 
52
  for i in range(1, 11):
53
- st.markdown(f"### Câu hỏi {i}")
 
54
  q_text = st.text_input(f"Nội dung câu hỏi {i}", key=f"q{i}")
55
 
56
  options = []
@@ -58,9 +80,9 @@ if role == "Quiz Creator":
58
  opt = st.text_input(f"Đáp án {j}", key=f"q{i}_opt{j}")
59
  options.append(opt)
60
 
61
- # Chọn đáp án đúng bằng TEXT
62
  correct = st.selectbox(
63
- f"Đáp án đúng của câu {i} (theo nội dung text)",
64
  options,
65
  key=f"q{i}_correct"
66
  )
@@ -71,91 +93,87 @@ if role == "Quiz Creator":
71
  "correct": correct
72
  })
73
 
74
- # Lưu quiz
75
- if st.button("Lưu Quiz"):
76
  valid = all(q["question"] and all(q["options"]) for q in questions)
77
 
78
  if not quiz_name:
79
- st.error("Nhập tên quiz")
 
80
  elif not valid:
81
- st.error("Nhập đầy đủ câu hỏi và đáp án")
 
82
  else:
83
- url = f"{FIREBASE_URL}/master_quizzes/{quiz_name}.json?auth={FIREBASE_AUTH}"
84
- requests.put(url, json={"questions": questions})
85
- st.success(f"Đã lưu quiz '{quiz_name}' với 10 câu hỏi!")
 
 
 
 
 
86
 
87
- # ================================
88
- # STUDENT EVALUATION (UPDATED)
89
- # ================================
90
- elif choice == "Student Evaluation":
91
- st.header("Student Evaluation & Feedback")
92
 
93
- # Nút Refresh
94
  if st.button("🔄 Refresh Data"):
95
  st.cache_data.clear()
96
  st.rerun()
97
 
98
- # Lấy danh sách toàn bộ student
99
- students = fetch_data(FIREBASE_URL + "/Students.json")
 
100
  if not students:
101
- st.warning("No student data found!")
102
  st.stop()
103
 
 
104
  student_ids = list(students.keys())
105
- selected_id = st.selectbox("Select Student ID", student_ids)
106
 
107
- student_info = students[selected_id]
 
108
 
109
  st.subheader("Student Information")
110
- st.write(f"**Name:** {student_info.get('Name','')}")
111
- st.write(f"**Class:** {student_info.get('Class','')}")
112
 
113
- # Lấy danh sách Quiz của student (Quiz1, Quiz2, ...)
114
- quiz_keys = [k for k in student_info.keys() if k.startswith("Quiz")]
115
 
116
- if not quiz_keys:
117
- st.info("Student has no quiz data yet.")
118
- st.stop()
119
-
120
- # Chuẩn bị bảng hiển thị
121
- table_rows = []
122
  for q in quiz_keys:
123
- qdata = student_info[q]
124
 
125
- score = qdata.get("Score", "")
126
- time = qdata.get("Time", "")
127
- fb_text = qdata.get("Feedback", "")
128
- fb_flag = "Yes" if fb_text else "No"
129
 
130
- table_rows.append({
131
  "Quiz": q,
132
  "Score": score,
133
  "Time": time,
134
- "Feedbacked": fb_flag
135
  })
136
 
137
- st.subheader("Quiz Overview")
138
- st.table(table_rows)
 
139
 
140
- # -------- Feedback Section --------
141
- st.subheader("Give Feedback")
142
 
143
- selected_quiz = st.selectbox("Select quiz for feedback", quiz_keys)
 
144
 
145
- # Nếu quiz đã có Feedback -> hiển thị
146
- existing_fb = student_info[selected_quiz].get("Feedback", "")
147
  if existing_fb:
148
- st.info(f"Existing feedback for **{selected_quiz}**:\n\n{existing_fb}")
149
-
150
- feedback_text = st.text_area("Enter new feedback")
151
 
152
- if st.button("Submit Feedback"):
153
- update_path = f"/Students/{selected_id}/{selected_quiz}/Feedback.json"
154
- result = update_data(FIREBASE_URL + update_path, feedback_text)
155
-
156
- if result is not None:
157
- st.success(f"Feedback saved for {selected_quiz}!")
158
- st.rerun()
159
- else:
160
- st.error("Failed to save feedback.")
161
 
 
 
 
 
 
2
  import requests
3
  import pandas as pd
4
 
5
+ # ===============================
6
  # Firebase config từ secrets.toml
7
+ # ===============================
8
  FIREBASE_URL = st.secrets["firebase_database_url"]
9
  FIREBASE_AUTH = st.secrets["firebase_api_key"]
10
 
 
 
 
 
 
11
 
12
+ # ===============================
13
+ # Helper functions
14
+ # ===============================
15
+ def firebase_get(path):
16
+ url = f"{FIREBASE_URL}/{path}.json?auth={FIREBASE_AUTH}"
17
+ try:
18
+ res = requests.get(url)
19
+ return res.json() if res.status_code == 200 else None
20
+ except:
21
+ return None
22
 
 
 
 
 
23
 
24
+ def firebase_put(path, data):
25
+ url = f"{FIREBASE_URL}/{path}.json?auth={FIREBASE_AUTH}"
26
+ try:
27
+ res = requests.put(url, json=data)
28
+ return res.json() if res.status_code == 200 else None
29
+ except:
30
+ return None
31
+
32
+
33
+ # ===============================
34
+ # SIDEBAR MENU
35
+ # ===============================
36
+ st.sidebar.title("SmartEdu System")
37
+ menu = st.sidebar.selectbox("Select Mode", ["Quiz Creator", "Student Evaluation"])
38
+
39
+
40
+ # ===============================
41
  # QUIZ CREATOR
42
+ # ===============================
43
+ if menu == "Quiz Creator":
44
+
45
+ st.header("Quiz Creator Login")
46
+
47
+ # Session Login
48
+ if "creator_login" not in st.session_state:
49
+ st.session_state.creator_login = False
50
+
51
+ if not st.session_state.creator_login:
52
+ usr = st.text_input("Username")
53
+ pwd = st.text_input("Password", type="password")
54
+
55
+ if st.button("Login"):
56
+ if usr == "master" and pwd == "master":
57
+ st.session_state.creator_login = True
58
+ st.success("Login successful!")
59
+ st.rerun()
60
  else:
61
+ st.error("Wrong username or password")
62
+
63
  st.stop()
64
 
65
+ # After login
66
+ st.success("You are logged in as Quiz Creator")
67
+ st.subheader("Create New Quiz")
68
 
69
+ quiz_name = st.text_input("Quiz Name (Example: Quiz1)")
70
 
 
 
 
71
  questions = []
72
+
73
  for i in range(1, 11):
74
+ st.markdown(f"### Question {i}")
75
+
76
  q_text = st.text_input(f"Nội dung câu hỏi {i}", key=f"q{i}")
77
 
78
  options = []
 
80
  opt = st.text_input(f"Đáp án {j}", key=f"q{i}_opt{j}")
81
  options.append(opt)
82
 
83
+ # Correct answer chosen by TEXT
84
  correct = st.selectbox(
85
+ f"Đáp án đúng của câu {i} (chọn theo text)",
86
  options,
87
  key=f"q{i}_correct"
88
  )
 
93
  "correct": correct
94
  })
95
 
96
+ if st.button("Save Quiz"):
 
97
  valid = all(q["question"] and all(q["options"]) for q in questions)
98
 
99
  if not quiz_name:
100
+ st.error("Quiz name required!")
101
+
102
  elif not valid:
103
+ st.error("Fill all questions and answers!")
104
+
105
  else:
106
+ firebase_put(f"master_quizzes/{quiz_name}", {"questions": questions})
107
+ st.success(f"Quiz '{quiz_name}' saved successfully!")
108
+
109
+
110
+ # ===============================
111
+ # STUDENT EVALUATION
112
+ # ===============================
113
+ elif menu == "Student Evaluation":
114
 
115
+ st.header("Student Evaluation")
 
 
 
 
116
 
117
+ # -------- Refresh Button --------
118
  if st.button("🔄 Refresh Data"):
119
  st.cache_data.clear()
120
  st.rerun()
121
 
122
+ # Load students
123
+ students = firebase_get("student_quizzes")
124
+
125
  if not students:
126
+ st.warning("No student data found.")
127
  st.stop()
128
 
129
+ # List of student IDs
130
  student_ids = list(students.keys())
 
131
 
132
+ selected_id = st.selectbox("Select Student ID", student_ids)
133
+ info = students[selected_id]
134
 
135
  st.subheader("Student Information")
136
+ st.write(f"**Name:** {info.get('Name', '')}")
137
+ st.write(f"**Class:** {info.get('Class', '')}")
138
 
139
+ # Find quiz keys
140
+ quiz_keys = [k for k in info.keys() if k.startswith("Quiz")]
141
 
142
+ # ---- Table Overview ----
143
+ table_data = []
 
 
 
 
144
  for q in quiz_keys:
145
+ qd = info[q]
146
 
147
+ score = qd.get("Score", "")
148
+ time = qd.get("Time", "")
149
+ fb = qd.get("Feedback", "")
150
+ fb_status = "Yes" if fb else "No"
151
 
152
+ table_data.append({
153
  "Quiz": q,
154
  "Score": score,
155
  "Time": time,
156
+ "Feedbacked": fb_status
157
  })
158
 
159
+ st.subheader("Quiz Overview Table")
160
+ df = pd.DataFrame(table_data)
161
+ st.dataframe(df, use_container_width=True)
162
 
163
+ # ----- FEEDBACK SECTION -----
164
+ st.subheader("Feedback")
165
 
166
+ choose_quiz = st.selectbox("Select quiz to feedback", quiz_keys)
167
+ selected_quiz_data = info[choose_quiz]
168
 
169
+ # Show existing feedback
170
+ existing_fb = selected_quiz_data.get("Feedback", "")
171
  if existing_fb:
172
+ st.info(f"📌 Existing feedback:\n\n{existing_fb}")
 
 
173
 
174
+ feedback = st.text_area("Enter new feedback")
 
 
 
 
 
 
 
 
175
 
176
+ if st.button("Send Feedback"):
177
+ firebase_put(f"student_quizzes/{selected_id}/{choose_quiz}/Feedback", feedback)
178
+ st.success("Feedback sent successfully!")
179
+ st.rerun()