Spaces:
Runtime error
Runtime error
Merge pull request #5 from VioletWizard-lim/claude/code-review-f3I3o
Browse files- app.py +165 -854
- components/__init__.py +0 -0
- components/chat_board.py +119 -0
- components/sidebar.py +238 -0
- components/teacher_dashboard.py +268 -0
- config.py +40 -0
- pages/__init__.py +0 -0
- pages/admin.py +35 -0
- pages/home.py +21 -0
- pages/lobby.py +34 -0
app.py
CHANGED
|
@@ -1,854 +1,165 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
import
|
| 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 |
-
if
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
if
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
if
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
st.session_state['page'] = "lobby"
|
| 167 |
-
|
| 168 |
-
def to_bool_flag(value):
|
| 169 |
-
if isinstance(value, bool): return value
|
| 170 |
-
if value is None: return False
|
| 171 |
-
return str(value).strip().lower() in {"true", "t", "1", "yes", "y", "on"}
|
| 172 |
-
|
| 173 |
-
def compact_ai_report_output(text):
|
| 174 |
-
raw_lines = [str(line).strip() for line in str(text or "").splitlines()]
|
| 175 |
-
cleaned = [line for line in raw_lines if line and not line.startswith("#")]
|
| 176 |
-
if not cleaned: return ""
|
| 177 |
-
report_labels = ("핵심요약 1:", "핵심요약 2:", "핵심요약 3:", "베스트 학생:", "선정 이유:")
|
| 178 |
-
normalized_text = " ".join(cleaned)
|
| 179 |
-
if report_labels[0] in normalized_text:
|
| 180 |
-
for label in report_labels[1:]:
|
| 181 |
-
normalized_text = normalized_text.replace(f" {label}", f"\n{label}")
|
| 182 |
-
normalized_text = normalized_text.replace(label, f"\n{label}")
|
| 183 |
-
normalized_lines = [line.strip() for line in normalized_text.splitlines() if line.strip()]
|
| 184 |
-
return "\n".join(normalized_lines[:5])
|
| 185 |
-
|
| 186 |
-
# ==========================================
|
| 187 |
-
# [3] 홈/네비게이션
|
| 188 |
-
# ==========================================
|
| 189 |
-
if st.session_state['page'] != "home":
|
| 190 |
-
col_home_btn, _ = st.columns([1, 7])
|
| 191 |
-
with col_home_btn:
|
| 192 |
-
if st.button("🏠 홈", use_container_width=True):
|
| 193 |
-
st.session_state['page'] = "home"
|
| 194 |
-
st.session_state['joined'] = False
|
| 195 |
-
st.session_state['teacher_auth'] = False
|
| 196 |
-
st.rerun()
|
| 197 |
-
|
| 198 |
-
if st.session_state['page'] == "home":
|
| 199 |
-
st.title("🏠 말자취(Talk-Trace) AI 홈")
|
| 200 |
-
st.markdown(
|
| 201 |
-
"""
|
| 202 |
-
### 사용 방법 (간단 안내)
|
| 203 |
-
1. **대기실로 이동** 버튼을 눌러 시작합니다.
|
| 204 |
-
2. 왼쪽 사이드바에서 **학생/교사 모드**를 선택합니다.
|
| 205 |
-
3. 접속할 **토론/토의방**을 선택하고 입장합니다.
|
| 206 |
-
4. 주제에 맞게 의견을 작성하고 제출하면 실시간 보드에 반영됩니다.
|
| 207 |
-
---
|
| 208 |
-
- 교사 모드에서는 방 개설/관리 및 대시보드 기능을 사용할 수 있습니다.
|
| 209 |
-
- 언제든 왼쪽 상단의 **🏠 홈** 버튼으로 이 화면으로 돌아올 수 있습니다.
|
| 210 |
-
"""
|
| 211 |
-
)
|
| 212 |
-
if st.button("🚀 대기실로 이동", type="primary", use_container_width=True):
|
| 213 |
-
st.session_state['page'] = "lobby"
|
| 214 |
-
st.rerun()
|
| 215 |
-
st.stop()
|
| 216 |
-
|
| 217 |
-
# ==========================================
|
| 218 |
-
# [4] 사이드바
|
| 219 |
-
# ==========================================
|
| 220 |
-
with st.sidebar:
|
| 221 |
-
st.header("👤 접속 권한")
|
| 222 |
-
user_role = st.radio("모드 선택", ["학생", "교사"], on_change=reset_joined_state)
|
| 223 |
-
st.divider()
|
| 224 |
-
|
| 225 |
-
try:
|
| 226 |
-
all_rooms = fetch_room_names(supabase)
|
| 227 |
-
except Exception:
|
| 228 |
-
all_rooms = []
|
| 229 |
-
|
| 230 |
-
room_name = ""
|
| 231 |
-
teacher_auth = False
|
| 232 |
-
admin_auth = False
|
| 233 |
-
student_number = ""
|
| 234 |
-
teacher_id_for_scope = st.session_state.get("teacher_id", "")
|
| 235 |
-
|
| 236 |
-
if user_role == "교사":
|
| 237 |
-
auth_mode = st.radio("교사 계정", ["로그인", "ID/PW 신청"], horizontal=True)
|
| 238 |
-
|
| 239 |
-
if auth_mode == "로그인":
|
| 240 |
-
with st.form("teacher_login_form"):
|
| 241 |
-
teacher_id_input = st.text_input("교사 ID", key="teacher_id_input")
|
| 242 |
-
teacher_pw_input = st.text_input("교사 PW", type="password", key="teacher_pw_input")
|
| 243 |
-
login_submitted = st.form_submit_button("교사 로그인", use_container_width=True)
|
| 244 |
-
|
| 245 |
-
if login_submitted:
|
| 246 |
-
id_ok, safe_teacher_id, id_error_code, id_error_message = validate_teacher_credential(teacher_id_input, field_name="교사 ID", max_len=60)
|
| 247 |
-
pw_ok, safe_pw, pw_error_code, pw_error_message = validate_teacher_credential(teacher_pw_input, field_name="교사 PW", max_len=60)
|
| 248 |
-
if not id_ok:
|
| 249 |
-
st.error(f"❌ {id_error_message} ({id_error_code})")
|
| 250 |
-
st.stop()
|
| 251 |
-
if not pw_ok:
|
| 252 |
-
st.error(f"❌ {pw_error_message} ({pw_error_code})")
|
| 253 |
-
st.stop()
|
| 254 |
-
account = fetch_teacher_account(supabase, safe_teacher_id)
|
| 255 |
-
if isinstance(account, dict) and account.get("_query_failed"):
|
| 256 |
-
st.session_state['teacher_auth'] = False
|
| 257 |
-
st.session_state['admin_auth'] = False
|
| 258 |
-
st.session_state['teacher_id'] = ""
|
| 259 |
-
redirect_from_admin_page_if_needed()
|
| 260 |
-
st.error("🚨 교사 계정 조회에 실패했습니다. Supabase RLS 정책/권한 및 DB 연결 상태를 확인해 주세요.")
|
| 261 |
-
elif not account:
|
| 262 |
-
st.session_state['teacher_auth'] = False
|
| 263 |
-
st.session_state['admin_auth'] = False
|
| 264 |
-
st.session_state['teacher_id'] = ""
|
| 265 |
-
redirect_from_admin_page_if_needed()
|
| 266 |
-
st.error("🚨 등록되지 않은 교사 ID입니다.")
|
| 267 |
-
if not using_service_role_key():
|
| 268 |
-
st.warning(
|
| 269 |
-
"⚠️ 현재 앱이 SERVICE ROLE KEY 없이 동작 중입니다. "
|
| 270 |
-
"teacher_accounts 테이블에 RLS 정책이 없으면 Data API 조회 결과가 0건으로 나와 "
|
| 271 |
-
"등록된 계정도 미등록으로 보일 수 있습니다."
|
| 272 |
-
)
|
| 273 |
-
try:
|
| 274 |
-
supabase_url = str(_get_secret("SUPABASE_URL", ""))
|
| 275 |
-
project_ref = supabase_url.split("//", 1)[-1].split(".", 1)[0] if supabase_url else ""
|
| 276 |
-
if project_ref:
|
| 277 |
-
st.caption(f"현재 앱 연결 DB 프로젝트: `{project_ref}`")
|
| 278 |
-
except Exception:
|
| 279 |
-
pass
|
| 280 |
-
elif account.get("teacher_pw") != safe_pw:
|
| 281 |
-
st.session_state['teacher_auth'] = False
|
| 282 |
-
st.session_state['admin_auth'] = False
|
| 283 |
-
st.session_state['teacher_id'] = ""
|
| 284 |
-
redirect_from_admin_page_if_needed()
|
| 285 |
-
st.error("❌ 비밀번호가 일치하지 않습니다.")
|
| 286 |
-
elif not account.get("is_approved"):
|
| 287 |
-
st.session_state['teacher_auth'] = False
|
| 288 |
-
st.session_state['admin_auth'] = False
|
| 289 |
-
st.session_state['teacher_id'] = ""
|
| 290 |
-
redirect_from_admin_page_if_needed()
|
| 291 |
-
st.warning("⏳ 최고관리자 승인 후 로그인할 수 있습니다.")
|
| 292 |
-
else:
|
| 293 |
-
st.session_state['teacher_auth'] = True
|
| 294 |
-
st.session_state['admin_auth'] = to_bool_flag(account.get("is_admin", False))
|
| 295 |
-
st.session_state['teacher_id'] = safe_teacher_id
|
| 296 |
-
redirect_from_admin_page_if_needed()
|
| 297 |
-
if st.session_state['admin_auth']:
|
| 298 |
-
st.session_state['page'] = "admin_approval"
|
| 299 |
-
st.toast("✅ 관리자 계정 로그인 성공", icon="✅")
|
| 300 |
-
st.rerun()
|
| 301 |
-
else:
|
| 302 |
-
st.toast("✅ 교사 로그인 성공", icon="✅")
|
| 303 |
-
else:
|
| 304 |
-
req_teacher_id = st.text_input("신청할 교사 ID", key="req_teacher_id")
|
| 305 |
-
req_teacher_pw = st.text_input("신청할 교사 PW", type="password", key="req_teacher_pw")
|
| 306 |
-
if st.button("교사 계정 신청", type="primary", use_container_width=True):
|
| 307 |
-
id_ok, safe_id, id_error_code, id_error_message = validate_teacher_credential(req_teacher_id, field_name="교사 ID", max_len=60)
|
| 308 |
-
pw_ok, safe_pw, pw_error_code, pw_error_message = validate_teacher_credential(req_teacher_pw, field_name="교사 PW", max_len=60)
|
| 309 |
-
if not id_ok:
|
| 310 |
-
st.error(f"❌ {id_error_message} ({id_error_code})")
|
| 311 |
-
elif not pw_ok:
|
| 312 |
-
st.error(f"❌ {pw_error_message} ({pw_error_code})")
|
| 313 |
-
elif fetch_teacher_account(supabase, safe_id):
|
| 314 |
-
st.warning("이미 존재하는 ID입니다. 다른 ID를 사용해 주세요.")
|
| 315 |
-
else:
|
| 316 |
-
req_res = request_teacher_account(supabase, safe_id, safe_pw)
|
| 317 |
-
if req_res is not None:
|
| 318 |
-
st.success("신청 완료! 최고관리자 승인 후 로그인할 수 있습니다.")
|
| 319 |
-
|
| 320 |
-
teacher_auth = st.session_state['teacher_auth']
|
| 321 |
-
admin_auth = st.session_state['admin_auth']
|
| 322 |
-
teacher_id_for_scope = st.session_state.get("teacher_id", "")
|
| 323 |
-
|
| 324 |
-
if teacher_auth:
|
| 325 |
-
st.caption(f"🔐 {teacher_id_for_scope} 로그인 중")
|
| 326 |
-
if st.button("🚪 로그아웃", use_container_width=True):
|
| 327 |
-
st.session_state['teacher_auth'] = False
|
| 328 |
-
st.session_state['admin_auth'] = False
|
| 329 |
-
st.session_state['teacher_id'] = ""
|
| 330 |
-
st.session_state['joined'] = False
|
| 331 |
-
st.session_state['page'] = "lobby"
|
| 332 |
-
st.rerun()
|
| 333 |
-
st.divider()
|
| 334 |
-
|
| 335 |
-
if teacher_auth and admin_auth:
|
| 336 |
-
st.caption("관리자 바로가기")
|
| 337 |
-
if st.button("📝 ID 요청 수락", use_container_width=True):
|
| 338 |
-
st.session_state['page'] = "admin_approval"
|
| 339 |
-
st.rerun()
|
| 340 |
-
if st.button("🚪 말자취(Talk-Trace) AI 대기실", use_container_width=True):
|
| 341 |
-
st.session_state['page'] = "lobby"
|
| 342 |
-
st.rerun()
|
| 343 |
-
st.divider()
|
| 344 |
-
|
| 345 |
-
if teacher_auth:
|
| 346 |
-
if admin_auth:
|
| 347 |
-
existing_rooms = all_rooms
|
| 348 |
-
else:
|
| 349 |
-
if topic_owner_column_available():
|
| 350 |
-
existing_rooms = fetch_room_names_by_owner(supabase, teacher_id_for_scope)
|
| 351 |
-
else:
|
| 352 |
-
existing_rooms = []
|
| 353 |
-
st.warning("교사별 방 조회를 위해 topic.created_by_teacher_id(권장) 또는 topic.created_by 컬럼이 필요합니다.")
|
| 354 |
-
|
| 355 |
-
room_opt = st.radio("방 관리", ["기존 방 선택", "새 방 만들기"])
|
| 356 |
-
if room_opt == "기존 방 선택" and existing_rooms:
|
| 357 |
-
room_name = st.selectbox("토론/토의방 목록", existing_rooms)
|
| 358 |
-
else:
|
| 359 |
-
new_room = st.text_input("새로 만들 방 이름 (예: 1학년 3반)")
|
| 360 |
-
new_title = st.text_input("주제 직접 입력 (예: 인공지능 윤리)")
|
| 361 |
-
new_mode = st.radio("진행 방식", ["⚔️ 찬반 토론", "💡 자유 토의"], horizontal=True)
|
| 362 |
-
new_pw = st.text_input("🔒 학생 입장용 암호 (비워두면 공개방)")
|
| 363 |
-
if st.button("새 방 개설하기", type="primary"):
|
| 364 |
-
room_ok, safe_new_room, room_error_code, room_error_message = validate_room_name(new_room, max_len=MAX_ROOM_NAME_LEN)
|
| 365 |
-
title_ok, safe_new_title, title_error_code, title_error_message = validate_opinion_content(new_title, max_len=MAX_TOPIC_LEN)
|
| 366 |
-
entry_ok, safe_new_pw, entry_error_code, entry_error_message = validate_entry_code(new_pw, max_len=MAX_ENTRY_CODE_LEN)
|
| 367 |
-
can_store_room_pw = topic_entry_code_column_available()
|
| 368 |
-
if not room_ok:
|
| 369 |
-
st.error(f"❌ {room_error_message} ({room_error_code})")
|
| 370 |
-
elif not title_ok:
|
| 371 |
-
st.error(f"❌ {title_error_message} ({title_error_code})")
|
| 372 |
-
elif not entry_ok:
|
| 373 |
-
st.error(f"❌ {entry_error_message} ({entry_error_code})")
|
| 374 |
-
elif safe_new_pw and not can_store_room_pw:
|
| 375 |
-
st.error("현재 DB 구조에서는 방 비밀번호 저장을 지원하지 않습니다.")
|
| 376 |
-
elif safe_new_room and safe_new_title:
|
| 377 |
-
res = upsert_topic_room(
|
| 378 |
-
supabase=supabase, room_name=safe_new_room, title=safe_new_title,
|
| 379 |
-
mode=new_mode, entry_code=safe_new_pw, created_by=teacher_id_for_scope,
|
| 380 |
-
)
|
| 381 |
-
if res is not None:
|
| 382 |
-
st.success(f"'{safe_new_room}' 방이 개설되었습니다! '기존 방 선택'을 눌러 입장하세요.")
|
| 383 |
-
room_name = ""
|
| 384 |
-
else:
|
| 385 |
-
st.session_state['teacher_auth'] = False
|
| 386 |
-
st.session_state['admin_auth'] = False
|
| 387 |
-
st.session_state['teacher_id'] = ""
|
| 388 |
-
redirect_from_admin_page_if_needed()
|
| 389 |
-
student_number = st.text_input("학번", key="student_number_input", placeholder="예: 1101")
|
| 390 |
-
if all_rooms:
|
| 391 |
-
room_name = st.selectbox("🏠 접속할 방 선택", all_rooms)
|
| 392 |
-
else:
|
| 393 |
-
st.warning("선생님이 아직 열어둔 방이 없습니다.")
|
| 394 |
-
room_name = ""
|
| 395 |
-
|
| 396 |
-
if user_role == "학생":
|
| 397 |
-
student_name = normalize_user_text(student_number, max_len=20)
|
| 398 |
-
else:
|
| 399 |
-
student_name = "교사"
|
| 400 |
-
|
| 401 |
-
if room_name and room_name != st.session_state['current_room']:
|
| 402 |
-
prev_room = st.session_state['current_room']
|
| 403 |
-
st.session_state['current_room'] = room_name
|
| 404 |
-
st.session_state['ai_hint_text'] = ""
|
| 405 |
-
st.session_state['ai_report_text'] = ""
|
| 406 |
-
st.session_state['ai_result_text'] = ""
|
| 407 |
-
if st.session_state['joined']:
|
| 408 |
-
st.session_state['joined'] = False
|
| 409 |
-
log_audit("room_switched_to_lobby", room_name=room_name, actor_name=student_name, role=user_role, previous_room=prev_room)
|
| 410 |
-
st.rerun()
|
| 411 |
-
|
| 412 |
-
if st.session_state['joined']:
|
| 413 |
-
st.divider()
|
| 414 |
-
if st.button("🚪 방 나가기 (대기실로)"):
|
| 415 |
-
st.session_state['joined'] = False
|
| 416 |
-
st.rerun()
|
| 417 |
-
|
| 418 |
-
if st.session_state['page'] == "admin_approval":
|
| 419 |
-
if not (user_role == "교사" and teacher_auth and admin_auth):
|
| 420 |
-
st.session_state['page'] = "lobby"
|
| 421 |
-
st.toast("관리자 페이지에서 나와 대기실로 이동했습니다.", icon="ℹ️")
|
| 422 |
-
st.rerun()
|
| 423 |
-
st.title("🛠️ 관리자 ID 요청 수락 페이지")
|
| 424 |
-
render_admin_approval_panel()
|
| 425 |
-
st.stop()
|
| 426 |
-
|
| 427 |
-
# ==========================================
|
| 428 |
-
# [5] 대기실
|
| 429 |
-
# ==========================================
|
| 430 |
-
if not st.session_state['joined']:
|
| 431 |
-
st.title("🚪 말자취(Talk-Trace) AI 대기실")
|
| 432 |
-
if user_role == "교사" and not teacher_auth:
|
| 433 |
-
st.warning("🚨 승인된 교사 계정으로 로그인해야 입장할 수 있습니다.")
|
| 434 |
-
elif not room_name.strip():
|
| 435 |
-
st.error("🚨 접속할 방을 먼저 선택해 주세요.")
|
| 436 |
-
else:
|
| 437 |
-
if user_role == "학생":
|
| 438 |
-
student_pw = st.text_input("🔒 방 입장 암호 (공개방이면 비워두세요)", type="password")
|
| 439 |
-
if st.button(f"🚀 '{room_name}' 입장하기", type="primary", use_container_width=True):
|
| 440 |
-
real_pw = fetch_room_entry_code(supabase, room_name)
|
| 441 |
-
if real_pw is None:
|
| 442 |
-
st.error("🚨 방 암호 정보를 확인할 수 없어 입장을 차단했습니다. 잠시 후 다시 시도해 주세요.")
|
| 443 |
-
elif real_pw and student_pw != real_pw:
|
| 444 |
-
st.error("❌ 암호가 틀렸습니다.")
|
| 445 |
-
elif not normalize_user_text(student_number, max_len=20):
|
| 446 |
-
st.error("❌ 학번을 입력해야 입장할 수 있습니다.")
|
| 447 |
-
else:
|
| 448 |
-
st.session_state['joined'] = True
|
| 449 |
-
st.rerun()
|
| 450 |
-
else:
|
| 451 |
-
if AUTO_JOIN_ON_REFRESH and teacher_auth:
|
| 452 |
-
st.session_state['joined'] = True; st.rerun()
|
| 453 |
-
if st.button(f"🚀 '{room_name}' 관리자 권한으로 입장", type="primary", use_container_width=True):
|
| 454 |
-
st.session_state['joined'] = True; st.rerun()
|
| 455 |
-
st.stop()
|
| 456 |
-
|
| 457 |
-
# ==========================================
|
| 458 |
-
# [6] 메인 화면 (의견 입력부)
|
| 459 |
-
# ==========================================
|
| 460 |
-
topic_data = fetch_topic_data(supabase, room_name)
|
| 461 |
-
current_topic = topic_data.get('title', "자유 주제로 대화해 봅시다.")
|
| 462 |
-
current_mode = topic_data.get('mode', "⚔️ 찬반 토론")
|
| 463 |
-
act_type = "토론" if "토론" in current_mode else "토의"
|
| 464 |
-
|
| 465 |
-
st.title(f"🎙️ 말자취(Talk-Trace) AI [{room_name}]")
|
| 466 |
-
st.info(f"**현재 주제:** {current_topic} ({current_mode})")
|
| 467 |
-
|
| 468 |
-
st.subheader("🗣️ 내 의견 작성")
|
| 469 |
-
col_input, col_stt = st.columns([4, 1])
|
| 470 |
-
with col_input:
|
| 471 |
-
user_input = st.text_area("의견을 입력하세요", key=f"input_{st.session_state['reset_key']}", height=80, label_visibility="collapsed")
|
| 472 |
-
opts = ["🔵 찬성", "🔴 반대"] if current_mode == "⚔️ 찬반 토론" else ["💡 아이디어", "➕ 보충", "❓ 질문"]
|
| 473 |
-
sentiment = st.radio("의견 성격", opts, horizontal=True)
|
| 474 |
-
|
| 475 |
-
with col_stt:
|
| 476 |
-
st.components.v1.html(
|
| 477 |
-
"""
|
| 478 |
-
<button id="stt-btn" style="width:100%; height:80px; font-weight:bold; border-radius:10px; background-color:#e8f0fe; border:1px solid #1a73e8; color:#1a73e8; cursor:pointer;">🎤 음성 입력 시작</button>
|
| 479 |
-
<p id="status" style="font-size:11px; color:gray; text-align:center; margin-top:5px;">대기 중...</p>
|
| 480 |
-
<script>
|
| 481 |
-
const btn = document.getElementById('stt-btn');
|
| 482 |
-
const status = document.getElementById('status');
|
| 483 |
-
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
|
| 484 |
-
recognition.lang = 'ko-KR';
|
| 485 |
-
let isRecognizing = false;
|
| 486 |
-
btn.onclick = () => { if (!isRecognizing) recognition.start(); else recognition.stop(); };
|
| 487 |
-
recognition.onstart = () => { isRecognizing = true; status.innerText = "듣는 중..."; btn.style.backgroundColor = "#ff4b4b"; btn.style.color = "white"; btn.innerHTML = "🛑 음성 입력 중지"; };
|
| 488 |
-
recognition.onresult = (event) => {
|
| 489 |
-
const text = event.results[0][0].transcript;
|
| 490 |
-
const textArea = window.parent.document.querySelector('textarea[aria-label="의견을 입력하세요"]');
|
| 491 |
-
if (textArea) {
|
| 492 |
-
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
|
| 493 |
-
nativeInputValueSetter.call(textArea, textArea.value + " " + text);
|
| 494 |
-
textArea.dispatchEvent(new Event('input', { bubbles: true }));
|
| 495 |
-
status.innerText = "입력 완료!";
|
| 496 |
-
}
|
| 497 |
-
};
|
| 498 |
-
recognition.onend = () => { isRecognizing = false; setTimeout(() => { status.innerText = "대기 중..."; btn.style.backgroundColor = "#e8f0fe"; btn.style.color = "#1a73e8"; btn.innerHTML = "🎤 음성 입력 시작"; }, 1500); };
|
| 499 |
-
</script>
|
| 500 |
-
""", height=120
|
| 501 |
-
)
|
| 502 |
-
|
| 503 |
-
if st.button("의견 제출", use_container_width=True, type="primary"):
|
| 504 |
-
input_ok, safe_input, input_error_code, input_error_message = validate_opinion_content(user_input, max_len=700)
|
| 505 |
-
student_ok, safe_student_name, student_error_code, student_error_message = validate_student_name(student_name, max_len=MAX_STUDENT_NAME_LEN)
|
| 506 |
-
student_number_ok, safe_student_number, student_number_error_code, student_number_error_message = validate_student_name(student_number, max_len=20)
|
| 507 |
-
if not student_number_ok and user_role == "학생":
|
| 508 |
-
st.error(f"❌ {student_number_error_message} ({student_number_error_code})")
|
| 509 |
-
st.stop()
|
| 510 |
-
if user_role == "학생" and (not safe_student_name or safe_student_name == "익명"):
|
| 511 |
-
safe_student_name = safe_student_number or "학번미입력"
|
| 512 |
-
if input_ok and safe_input:
|
| 513 |
-
now = get_kst_now_str()
|
| 514 |
-
author_role_for_submit = "교사" if user_role == "교사" else "학생"
|
| 515 |
-
client_ip = get_client_ip()
|
| 516 |
-
insert_payload = {
|
| 517 |
-
"room_name": room_name, "timestamp": now, "student_name": safe_student_name,
|
| 518 |
-
"content": safe_input, "sentiment": sentiment, "author_role": author_role_for_submit
|
| 519 |
-
}
|
| 520 |
-
if debate_ip_column_available() and client_ip:
|
| 521 |
-
insert_payload["ip_address"] = client_ip
|
| 522 |
-
try:
|
| 523 |
-
res = submit_opinion(supabase, insert_payload)
|
| 524 |
-
if res is None: st.stop()
|
| 525 |
-
log_audit("opinion_submitted", room_name=room_name, actor_name=safe_student_name, role=author_role_for_submit, sentiment=sentiment, client_ip=client_ip if client_ip else "N/A")
|
| 526 |
-
st.session_state['reset_key'] += 1
|
| 527 |
-
st.rerun()
|
| 528 |
-
except Exception as e:
|
| 529 |
-
st.error(f"저장 실패: {e}")
|
| 530 |
-
else:
|
| 531 |
-
st.warning(f"{input_error_message} ({input_error_code})")
|
| 532 |
-
|
| 533 |
-
st.divider()
|
| 534 |
-
|
| 535 |
-
# ==========================================
|
| 536 |
-
# [7] 실시간 업데이트 영역
|
| 537 |
-
# ==========================================
|
| 538 |
-
def live_chat_board_core():
|
| 539 |
-
# ✅ Phase 2 핵심: fetch_live_messages 이중 호출 제거
|
| 540 |
-
# 기존: limit=300, limit=2000 각각 2회 호출 → Supabase 요청 2배 낭비
|
| 541 |
-
# 개선: DASHBOARD_FETCH_LIMIT(2000)으로 1회만 호출 후 보드/통계 모두 재사용
|
| 542 |
-
all_df = with_fallback_author_role(
|
| 543 |
-
fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT)
|
| 544 |
-
)
|
| 545 |
-
# 실시간 보드용: 최신 300건 슬라이싱 (id desc 정렬이므로 앞에서 자름)
|
| 546 |
-
opinion_df = all_df.head(LIVE_BOARD_FETCH_LIMIT) if not all_df.empty else all_df
|
| 547 |
-
# 통계용: 전체 2000건 사용
|
| 548 |
-
stats_opinion_df = all_df
|
| 549 |
-
|
| 550 |
-
with st.expander("📊 실시간 의견 통계 보기 (클릭하여 펼치기)"):
|
| 551 |
-
if not stats_opinion_df.empty:
|
| 552 |
-
left_col, right_col = st.columns(2)
|
| 553 |
-
with left_col:
|
| 554 |
-
st.caption("감정 분포 그래프")
|
| 555 |
-
live_pie_fig = px.pie(stats_opinion_df, names="sentiment", hole=0.4, height=320)
|
| 556 |
-
live_pie_fig.update_layout(font={"family": UI_FONT_FAMILY})
|
| 557 |
-
st.plotly_chart(live_pie_fig, use_container_width=True, config={'displayModeBar': False, 'scrollZoom': False})
|
| 558 |
-
with right_col:
|
| 559 |
-
st.caption("누적 토의/토론 워드클라우드")
|
| 560 |
-
frequencies = build_word_frequencies(stats_opinion_df["content"])
|
| 561 |
-
if frequencies:
|
| 562 |
-
st.markdown(build_circular_wordcloud_html(frequencies), unsafe_allow_html=True)
|
| 563 |
-
top_words = ", ".join([f"{word}({count})" for word, count in frequencies.most_common(8)])
|
| 564 |
-
st.caption(f"상위 키워드: {top_words}")
|
| 565 |
-
else:
|
| 566 |
-
st.info("워드클라우드를 만들 단어가 아직 부족합니다.")
|
| 567 |
-
else:
|
| 568 |
-
st.write("데이터 수집 중...")
|
| 569 |
-
|
| 570 |
-
col_board_title, col_board_ref = st.columns([8, 2])
|
| 571 |
-
with col_board_title:
|
| 572 |
-
st.subheader(f"💬 실시간 {act_type} 보드")
|
| 573 |
-
with col_board_ref:
|
| 574 |
-
if user_role == "교사" and teacher_auth:
|
| 575 |
-
st.button("🔄 실시간 보드 새로고침", use_container_width=True, key="refresh_chat_board")
|
| 576 |
-
|
| 577 |
-
if not opinion_df.empty:
|
| 578 |
-
teacher_df = opinion_df[opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 579 |
-
if not teacher_df.empty:
|
| 580 |
-
st.success(f"👨🏫 **선생님의 생각 힌트!** ➡️ {teacher_df.iloc[0]['content']}")
|
| 581 |
-
|
| 582 |
-
student_df = opinion_df[~opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 583 |
-
|
| 584 |
-
def delete_chat_msg(msg_id):
|
| 585 |
-
try:
|
| 586 |
-
if delete_opinion_message(supabase, msg_id) is None: return
|
| 587 |
-
log_audit("chat_deleted", room_name=room_name, actor_name=student_name, role=user_role, message_id=msg_id)
|
| 588 |
-
st.toast("의견이 즉시 삭제되었습니다.", icon="🗑️")
|
| 589 |
-
except Exception as e:
|
| 590 |
-
st.error(f"삭제 실패: {e}")
|
| 591 |
-
|
| 592 |
-
def render_msg(row):
|
| 593 |
-
formatted_timestamp = format_kst_datetime(row.get("timestamp", ""))
|
| 594 |
-
if user_role == "교사" and teacher_auth:
|
| 595 |
-
c_name, c_btn = st.columns([5, 1])
|
| 596 |
-
with c_name:
|
| 597 |
-
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 598 |
-
row_ip = str(row.get("ip_address", "")).strip() if hasattr(row, "get") else ""
|
| 599 |
-
if row_ip:
|
| 600 |
-
st.caption(f"IP: {mask_ip_for_teacher(row_ip)}")
|
| 601 |
-
with c_btn:
|
| 602 |
-
st.button("❌", key=f"del_{row['id']}", help="강제 삭제", on_click=delete_chat_msg, args=(row['id'],))
|
| 603 |
-
st.info(row['content'])
|
| 604 |
-
else:
|
| 605 |
-
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 606 |
-
st.info(row['content'])
|
| 607 |
-
st.write("")
|
| 608 |
-
|
| 609 |
-
if current_mode == "⚔️ 찬반 토론":
|
| 610 |
-
col_pro, col_con = st.columns(2)
|
| 611 |
-
with col_pro:
|
| 612 |
-
st.markdown("### 🔵 찬성 측")
|
| 613 |
-
with st.container(height=450):
|
| 614 |
-
for _, row in student_df[student_df['sentiment'] == '🔵 찬성'].iterrows(): render_msg(row)
|
| 615 |
-
with col_con:
|
| 616 |
-
st.markdown("### 🔴 반대 측")
|
| 617 |
-
with st.container(height=450):
|
| 618 |
-
for _, row in student_df[student_df['sentiment'] == '🔴 반대'].iterrows(): render_msg(row)
|
| 619 |
-
else:
|
| 620 |
-
col_idea, col_plus, col_q = st.columns(3)
|
| 621 |
-
with col_idea:
|
| 622 |
-
st.markdown("### 💡 아이디어")
|
| 623 |
-
with st.container(height=450):
|
| 624 |
-
for _, row in student_df[student_df['sentiment'] == '💡 아이디어'].iterrows(): render_msg(row)
|
| 625 |
-
with col_plus:
|
| 626 |
-
st.markdown("### ➕ 보충")
|
| 627 |
-
with st.container(height=450):
|
| 628 |
-
for _, row in student_df[student_df['sentiment'] == '➕ 보충'].iterrows(): render_msg(row)
|
| 629 |
-
with col_q:
|
| 630 |
-
st.markdown("### ❓ 질문")
|
| 631 |
-
with st.container(height=450):
|
| 632 |
-
for _, row in student_df[student_df['sentiment'] == '❓ 질문'].iterrows(): render_msg(row)
|
| 633 |
-
else:
|
| 634 |
-
st.info(f"아직 대화가 없습니다. 첫 {act_type} 의견을 남겨주세요!")
|
| 635 |
-
|
| 636 |
-
@st.fragment(run_every=LIVE_REFRESH_INTERVAL)
|
| 637 |
-
def live_chat_board_auto():
|
| 638 |
-
live_chat_board_core()
|
| 639 |
-
|
| 640 |
-
def live_chat_board_manual():
|
| 641 |
-
live_chat_board_core()
|
| 642 |
-
|
| 643 |
-
if st.session_state.get('is_working', False):
|
| 644 |
-
live_chat_board_manual()
|
| 645 |
-
else:
|
| 646 |
-
live_chat_board_auto()
|
| 647 |
-
|
| 648 |
-
# ==========================================
|
| 649 |
-
# [8] 교사 전용 대시보드
|
| 650 |
-
# ==========================================
|
| 651 |
-
if user_role == "교사" and teacher_auth:
|
| 652 |
-
st.divider()
|
| 653 |
-
col_dash_title, col_dash_refresh = st.columns([8, 2])
|
| 654 |
-
with col_dash_title:
|
| 655 |
-
st.header("👨🏫 교사 관리 대시보드")
|
| 656 |
-
with col_dash_refresh:
|
| 657 |
-
if st.button("🔄 대시보드 수동 새로고침", use_container_width=True):
|
| 658 |
-
st.rerun()
|
| 659 |
-
|
| 660 |
-
df_all = with_fallback_author_role(fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT))
|
| 661 |
-
|
| 662 |
-
st.subheader("📊 학생 참여도 현황")
|
| 663 |
-
if not df_all.empty:
|
| 664 |
-
student_only_df = df_all[(df_all['author_role'] == '학생') & ~df_all['student_name'].str.contains('익명|AI', na=False, regex=True)].copy()
|
| 665 |
-
if not student_only_df.empty:
|
| 666 |
-
counts = student_only_df['student_name'].astype(str).value_counts().reset_index()
|
| 667 |
-
counts.columns = ['학생 이름', '참여 횟수']
|
| 668 |
-
counts['학생 이름'] = counts['학생 이름'] + " "
|
| 669 |
-
fig = px.bar(counts, x='학생 이름', y='참여 횟수', text='참여 횟수', color='학생 이름')
|
| 670 |
-
fig.update_xaxes(type='category', title="")
|
| 671 |
-
fig.update_layout(yaxis_title="의견 수", dragmode=False, showlegend=False, font={"family": UI_FONT_FAMILY})
|
| 672 |
-
st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': False, 'displayModeBar': False})
|
| 673 |
-
else: st.info("실명 참여 데이터가 없습니다.")
|
| 674 |
-
else: st.info(f"{act_type} 데이터가 없습니다.")
|
| 675 |
-
|
| 676 |
-
st.divider()
|
| 677 |
-
|
| 678 |
-
@st.fragment
|
| 679 |
-
def teacher_hint_section():
|
| 680 |
-
st.subheader(f"💡 AI {act_type} 촉진 (Teacher-in-the-loop)")
|
| 681 |
-
st.info("AI 제안을 수정 후 전송하세요.")
|
| 682 |
-
|
| 683 |
-
def send_hint():
|
| 684 |
-
val = st.session_state.get('hint_input_widget', '').strip()
|
| 685 |
-
if val:
|
| 686 |
-
now = get_kst_now_str()
|
| 687 |
-
try:
|
| 688 |
-
res = create_teacher_hint(supabase, {
|
| 689 |
-
"room_name": room_name, "timestamp": now, "student_name": "👨🏫 선생님 (AI 보조)",
|
| 690 |
-
"content": val, "sentiment": "❓ 질문", "author_role": "교사"
|
| 691 |
-
})
|
| 692 |
-
if res is None: return
|
| 693 |
-
log_audit("teacher_hint_sent", room_name=room_name, actor_name=student_name, role=user_role)
|
| 694 |
-
st.session_state['hint_input_widget'] = ""
|
| 695 |
-
except Exception as e:
|
| 696 |
-
st.error(f"힌트 전송 실패: {e}")
|
| 697 |
-
|
| 698 |
-
if AI_HINT_ENABLED:
|
| 699 |
-
if st.button("🪄 AI 힌트 초안 생성", use_container_width=True):
|
| 700 |
-
st.toast("👀 AI가 대화 맥락을 읽고 있습니다...", icon="⏳")
|
| 701 |
-
with st.spinner("✍️ 예리한 질문을 작성하고 있습니다..."):
|
| 702 |
-
context = "\n".join(df_all['content'].tail(5).tolist()) if not df_all.empty else "대화 없음"
|
| 703 |
-
prompt = build_hint_prompt(act_type, current_topic, context)
|
| 704 |
-
res_text = generate_ai_response(
|
| 705 |
-
prompt, model_name=AI_MODEL_NAME, api_key=_get_secret("GEMINI_API_KEY", ""),
|
| 706 |
-
log_message="AI 힌트 생성 실패", room_name=room_name,
|
| 707 |
-
)
|
| 708 |
-
if res_text:
|
| 709 |
-
st.session_state['hint_input_widget'] = res_text.strip().split('\n')[0]
|
| 710 |
-
st.session_state['ai_hint_manual_mode'] = False
|
| 711 |
-
st.toast("✅ 힌트 작성 완료!", icon="🎉")
|
| 712 |
-
else:
|
| 713 |
-
st.session_state['ai_hint_manual_mode'] = True
|
| 714 |
-
st.toast("🚨 AI 호출 오류: 수동 모드로 전환되었습니다.", icon="❌")
|
| 715 |
-
else:
|
| 716 |
-
st.session_state['ai_hint_manual_mode'] = True
|
| 717 |
-
|
| 718 |
-
col_edit_txt, col_edit_btn = st.columns([8, 2])
|
| 719 |
-
with col_edit_txt:
|
| 720 |
-
st.text_input("선생님의 검토 및 수정", key="hint_input_widget", label_visibility="collapsed", placeholder="여기에 AI 힌트가 나타납니다.")
|
| 721 |
-
with col_edit_btn:
|
| 722 |
-
st.button("🚀 학생 화면 전송", use_container_width=True, type="primary", on_click=send_hint)
|
| 723 |
-
|
| 724 |
-
teacher_hint_section()
|
| 725 |
-
st.divider()
|
| 726 |
-
|
| 727 |
-
@st.fragment
|
| 728 |
-
def teacher_summary_section():
|
| 729 |
-
st.subheader(f"📝 수업 종료 및 전체 {act_type} 요약 리포트")
|
| 730 |
-
if st.button(f"{act_type} 요약 및 베스트 발언 추출 🪄", use_container_width=True):
|
| 731 |
-
st.toast("👀 AI가 전체 기록을 꼼꼼히 읽고 있습니다...", icon="⏳")
|
| 732 |
-
with st.spinner("✍️ 요약 리포트를 작성하고 있습니다..."):
|
| 733 |
-
if not df_all.empty:
|
| 734 |
-
full_history = "\n".join([f"[{row['student_name']} - {row['sentiment']}] {row['content']}" for _, row in df_all.iterrows()])
|
| 735 |
-
prompt = (
|
| 736 |
-
f"'{current_topic}' 주제의 고등학교 {act_type} 기록입니다.\n\n"
|
| 737 |
-
"[출력 형식 - 반드시 그대로]\n"
|
| 738 |
-
"핵심요약 1: ...\n핵심요약 2: ...\n핵심요약 3: ...\n베스트 학생: ...\n선정 이유: ...\n\n"
|
| 739 |
-
"[엄격한 규칙]\n"
|
| 740 |
-
"- 핵심요약 1,2,3과 베스트 학생, 선정이유를 줄바꿈을 하여 보기 편하게 합니다.\n"
|
| 741 |
-
"- 5~10줄로 출력합니다.\n- 제목/헤더(#,##,###), 소제목을 절대 쓰지 않습니다.\n"
|
| 742 |
-
"- 불필요한 서론/결론 없이 바로 결과만 출력합니다.\n\n"
|
| 743 |
-
f"기록:\n{full_history}"
|
| 744 |
-
)
|
| 745 |
-
res_text = generate_ai_response(
|
| 746 |
-
prompt, model_name=AI_MODEL_NAME, api_key=_get_secret("GEMINI_API_KEY", ""),
|
| 747 |
-
log_message="AI 요약 리포트 생성 실패", room_name=room_name,
|
| 748 |
-
)
|
| 749 |
-
if res_text:
|
| 750 |
-
st.session_state['ai_report_text'] = compact_ai_report_output(res_text)
|
| 751 |
-
st.toast("✅ 리포트 작성 완료!", icon="🎉")
|
| 752 |
-
else:
|
| 753 |
-
st.toast("🚨 AI 호출 오류가 발생했습니다.", icon="❌")
|
| 754 |
-
else:
|
| 755 |
-
st.toast("🚨 분석할 데이터가 없습니다.", icon="⚠️")
|
| 756 |
-
if st.session_state.get('ai_report_text'):
|
| 757 |
-
st.info(f"📊 **AI 수업 {act_type} 요약 리포트**")
|
| 758 |
-
report_html = html.escape(st.session_state['ai_report_text']).replace("\n", "<br>")
|
| 759 |
-
st.markdown(f"<div style='line-height:1.8;'>{report_html}</div>", unsafe_allow_html=True)
|
| 760 |
-
|
| 761 |
-
teacher_summary_section()
|
| 762 |
-
st.divider()
|
| 763 |
-
|
| 764 |
-
@st.fragment
|
| 765 |
-
def teacher_record_section():
|
| 766 |
-
def delete_selected_record():
|
| 767 |
-
del_id = st.session_state.get('del_record_dropdown')
|
| 768 |
-
if del_id:
|
| 769 |
-
try:
|
| 770 |
-
if delete_student_record(supabase, del_id) is None: return
|
| 771 |
-
log_audit("record_deleted", room_name=room_name, actor_name=student_name, role=user_role, record_id=del_id)
|
| 772 |
-
st.toast("기록이 삭제되었습니다.", icon="🗑️")
|
| 773 |
-
except Exception as e:
|
| 774 |
-
st.error(f"기록 삭제 실패: {e}")
|
| 775 |
-
|
| 776 |
-
col3, col4 = st.columns([1, 1])
|
| 777 |
-
with col3:
|
| 778 |
-
st.subheader("📥 활동 데이터 다운로드")
|
| 779 |
-
if not df_all.empty:
|
| 780 |
-
buffer = io.BytesIO()
|
| 781 |
-
with pd.ExcelWriter(buffer, engine='openpyxl') as writer: df_all.to_excel(writer, index=False)
|
| 782 |
-
st.download_button(f"{act_type} 전체 활동 로그 (Excel)", data=buffer.getvalue(), file_name=f"{room_name}_log_{get_kst_now().strftime('%Y%m%d_%H%M')}.xlsx")
|
| 783 |
-
|
| 784 |
-
with col4:
|
| 785 |
-
st.subheader("🤖 개인별 AI 세특 초안 생성")
|
| 786 |
-
student_list = student_only_df['student_name'].unique() if not df_all.empty else []
|
| 787 |
-
if len(student_list) > 0:
|
| 788 |
-
selected_student = st.selectbox("학생을 선택하세요", student_list)
|
| 789 |
-
if st.button(f"'{selected_student}' 세특 생성 🪄", use_container_width=True):
|
| 790 |
-
st.toast(f"👀 AI가 '{selected_student}' 학생의 활동을 분석합니다...", icon="⏳")
|
| 791 |
-
with st.spinner(f"✍️ '{selected_student}' 학생의 세특 초안 작성 중..."):
|
| 792 |
-
try:
|
| 793 |
-
student_data = df_all[df_all['student_name'] == selected_student]
|
| 794 |
-
debate_history = "\n".join([f"- [{row['sentiment']}] {row['content']}" for _, row in student_data.iterrows()])
|
| 795 |
-
prompt = build_record_prompt(act_type, current_topic, selected_student, debate_history)
|
| 796 |
-
res_text = generate_ai_response(
|
| 797 |
-
prompt, model_name=AI_MODEL_NAME, api_key=_get_secret("GEMINI_API_KEY", ""),
|
| 798 |
-
log_message="AI 세특 생성 실패", room_name=room_name, student=selected_student,
|
| 799 |
-
)
|
| 800 |
-
if res_text:
|
| 801 |
-
st.session_state['ai_result_text'] = res_text
|
| 802 |
-
now = get_kst_now_str()
|
| 803 |
-
save_res = save_student_record(supabase, {
|
| 804 |
-
"room_name": room_name, "timestamp": now,
|
| 805 |
-
"student_name": selected_student, "content": res_text
|
| 806 |
-
})
|
| 807 |
-
if save_res is None: raise RuntimeError("보관함 저장 실패")
|
| 808 |
-
st.toast("✅ 세특 생성 및 보관함 저장 완료!", icon="🎉")
|
| 809 |
-
else:
|
| 810 |
-
raise RuntimeError("AI 응답 비어있음")
|
| 811 |
-
except Exception as e:
|
| 812 |
-
logger.exception("세특 생성 후처리 실패")
|
| 813 |
-
st.toast("🚨 오류가 발생했습니다. 다시 시도해주세요.", icon="❌")
|
| 814 |
-
if st.session_state.get('ai_result_text'):
|
| 815 |
-
st.success("🤖 **개인별 세특 초안** (보관함에 자동 저장되었습니다)")
|
| 816 |
-
st.text_area("내용 수정 후 복사하여 사용하세요", value=st.session_state['ai_result_text'], height=200, label_visibility="collapsed")
|
| 817 |
-
else: st.info("실명 참여 학생이 없습니다.")
|
| 818 |
-
|
| 819 |
-
st.divider()
|
| 820 |
-
st.subheader("📂 저장된 세특 기록 보관함")
|
| 821 |
-
records_df = fetch_student_records(supabase, room_name, RECORDS_FETCH_LIMIT)
|
| 822 |
-
if not records_df.empty:
|
| 823 |
-
records_display_df = records_df.rename(columns={"id": "No.", "content": "세특 내용"})
|
| 824 |
-
records_html = records_display_df.to_html(index=False, escape=True)
|
| 825 |
-
st.markdown(f"<div class='records-db-table-wrap'>{records_html}</div>", unsafe_allow_html=True)
|
| 826 |
-
col_down, col_del = st.columns([1, 1])
|
| 827 |
-
with col_down:
|
| 828 |
-
buffer_records = io.BytesIO()
|
| 829 |
-
with pd.ExcelWriter(buffer_records, engine='openpyxl') as writer:
|
| 830 |
-
records_df.drop(columns=['id']).to_excel(writer, index=False)
|
| 831 |
-
st.download_button("📥 세특 보관함 다운로드 (Excel)", data=buffer_records.getvalue(), file_name=f"{room_name}_세특보관함.xlsx")
|
| 832 |
-
with col_del:
|
| 833 |
-
st.selectbox("🗑️ 삭제할 '고유 번호(No.)' 선택", records_df['id'].tolist(), key="del_record_dropdown")
|
| 834 |
-
st.button("선택한 세특 기록 영구 삭제", type="primary", on_click=delete_selected_record)
|
| 835 |
-
else: st.info("저장된 기록이 없습니다.")
|
| 836 |
-
|
| 837 |
-
teacher_record_section()
|
| 838 |
-
|
| 839 |
-
st.divider()
|
| 840 |
-
st.subheader("🚨 위험 구역 (방 폭파)")
|
| 841 |
-
with st.expander("이 방 전체 삭제하기 (클릭 시 펼쳐짐)", expanded=False):
|
| 842 |
-
if not ROOM_DESTROY_ENABLED:
|
| 843 |
-
st.warning("운영 안전 모드로 방 폭파 기능이 비활성화되어 있습니다.")
|
| 844 |
-
else:
|
| 845 |
-
st.error(f"🚨 경고: '{room_name}' 방의 모든 {act_type} 기록과 세특 보관함이 완전히 삭제됩니다.")
|
| 846 |
-
if st.button(f"네, '{room_name}' 방의 모든 데이터를 영구 삭제합니다", type="primary", use_container_width=True):
|
| 847 |
-
try:
|
| 848 |
-
if destroy_room_data(supabase, room_name) is None: st.stop()
|
| 849 |
-
log_audit("room_destroyed", room_name=room_name, actor_name=student_name, role=user_role)
|
| 850 |
-
st.success("성공적으로 파괴되었습니다.")
|
| 851 |
-
st.session_state['ai_result_text'] = ""
|
| 852 |
-
st.rerun()
|
| 853 |
-
except Exception as e:
|
| 854 |
-
st.error(f"삭제 중 오류 발생: {e}")
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
import streamlit as st
|
| 4 |
+
|
| 5 |
+
from db import (
|
| 6 |
+
debate_ip_column_available,
|
| 7 |
+
ensure_db_login,
|
| 8 |
+
fetch_topic_data,
|
| 9 |
+
init_db,
|
| 10 |
+
submit_opinion,
|
| 11 |
+
)
|
| 12 |
+
from config import APP_CSS, MAX_STUDENT_NAME_LEN
|
| 13 |
+
from utils import get_client_ip, get_kst_now_str, log_audit
|
| 14 |
+
from validators import normalize_user_text, validate_opinion_content, validate_student_name
|
| 15 |
+
from pages.home import render_home_page
|
| 16 |
+
from pages.lobby import render_lobby_page
|
| 17 |
+
from pages.admin import render_admin_page
|
| 18 |
+
from components.sidebar import render_sidebar
|
| 19 |
+
from components.chat_board import render_chat_board
|
| 20 |
+
from components.teacher_dashboard import render_teacher_dashboard
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger("talk_trace_ai")
|
| 23 |
+
if not logger.handlers:
|
| 24 |
+
logging.basicConfig(
|
| 25 |
+
level=logging.INFO,
|
| 26 |
+
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
supabase = init_db()
|
| 30 |
+
ensure_db_login(supabase)
|
| 31 |
+
|
| 32 |
+
st.set_page_config(page_title="말자취(Talk-Trace) AI", layout="wide")
|
| 33 |
+
st.markdown(APP_CSS, unsafe_allow_html=True)
|
| 34 |
+
|
| 35 |
+
if 'reset_key' not in st.session_state: st.session_state['reset_key'] = 0
|
| 36 |
+
if 'ai_result_text' not in st.session_state: st.session_state['ai_result_text'] = ""
|
| 37 |
+
if 'ai_hint_text' not in st.session_state: st.session_state['ai_hint_text'] = ""
|
| 38 |
+
if 'ai_report_text' not in st.session_state: st.session_state['ai_report_text'] = ""
|
| 39 |
+
if 'page' not in st.session_state: st.session_state['page'] = "home"
|
| 40 |
+
if 'current_room' not in st.session_state: st.session_state['current_room'] = ""
|
| 41 |
+
if 'joined' not in st.session_state: st.session_state['joined'] = False
|
| 42 |
+
if 'teacher_auth' not in st.session_state: st.session_state['teacher_auth'] = False
|
| 43 |
+
if 'admin_auth' not in st.session_state: st.session_state['admin_auth'] = False
|
| 44 |
+
if 'teacher_id' not in st.session_state: st.session_state['teacher_id'] = ""
|
| 45 |
+
if 'is_working' not in st.session_state: st.session_state['is_working'] = False
|
| 46 |
+
if 'ai_hint_manual_mode' not in st.session_state: st.session_state['ai_hint_manual_mode'] = False
|
| 47 |
+
|
| 48 |
+
if st.session_state['page'] != "home":
|
| 49 |
+
col_home_btn, _ = st.columns([1, 7])
|
| 50 |
+
with col_home_btn:
|
| 51 |
+
if st.button("🏠 홈", use_container_width=True):
|
| 52 |
+
st.session_state['page'] = "home"
|
| 53 |
+
st.session_state['joined'] = False
|
| 54 |
+
st.session_state['teacher_auth'] = False
|
| 55 |
+
st.rerun()
|
| 56 |
+
|
| 57 |
+
if st.session_state['page'] == "home":
|
| 58 |
+
render_home_page()
|
| 59 |
+
|
| 60 |
+
sidebar_ctx = render_sidebar(supabase)
|
| 61 |
+
user_role = sidebar_ctx['user_role']
|
| 62 |
+
room_name = sidebar_ctx['room_name']
|
| 63 |
+
teacher_auth = sidebar_ctx['teacher_auth']
|
| 64 |
+
admin_auth = sidebar_ctx['admin_auth']
|
| 65 |
+
student_name = sidebar_ctx['student_name']
|
| 66 |
+
student_number = sidebar_ctx['student_number']
|
| 67 |
+
|
| 68 |
+
if st.session_state['page'] == "admin_approval":
|
| 69 |
+
render_admin_page(supabase, user_role, teacher_auth, admin_auth)
|
| 70 |
+
|
| 71 |
+
if not st.session_state['joined']:
|
| 72 |
+
render_lobby_page(supabase, user_role, teacher_auth, room_name, student_number)
|
| 73 |
+
|
| 74 |
+
# === Joined room view ===
|
| 75 |
+
topic_data = fetch_topic_data(supabase, room_name)
|
| 76 |
+
current_topic = topic_data.get('title', "자유 주제로 대화해 봅시다.")
|
| 77 |
+
current_mode = topic_data.get('mode', "⚔️ 찬반 토론")
|
| 78 |
+
act_type = "토론" if "토론" in current_mode else "토의"
|
| 79 |
+
|
| 80 |
+
st.title(f"🎙️ 말자취(Talk-Trace) AI [{room_name}]")
|
| 81 |
+
st.info(f"**현재 주제:** {current_topic} ({current_mode})")
|
| 82 |
+
|
| 83 |
+
st.subheader("🗣️ 내 의견 작성")
|
| 84 |
+
col_input, col_stt = st.columns([4, 1])
|
| 85 |
+
with col_input:
|
| 86 |
+
user_input = st.text_area(
|
| 87 |
+
"의견을 입력하세요",
|
| 88 |
+
key=f"input_{st.session_state['reset_key']}",
|
| 89 |
+
height=80,
|
| 90 |
+
label_visibility="collapsed",
|
| 91 |
+
)
|
| 92 |
+
opts = ["🔵 찬성", "🔴 반대"] if current_mode == "⚔️ 찬반 토론" else ["💡 아이디어", "➕ 보충", "❓ 질문"]
|
| 93 |
+
sentiment = st.radio("의견 성격", opts, horizontal=True)
|
| 94 |
+
|
| 95 |
+
with col_stt:
|
| 96 |
+
st.components.v1.html(
|
| 97 |
+
"""
|
| 98 |
+
<button id="stt-btn" style="width:100%; height:80px; font-weight:bold; border-radius:10px; background-color:#e8f0fe; border:1px solid #1a73e8; color:#1a73e8; cursor:pointer;">🎤 음성 입력 시작</button>
|
| 99 |
+
<p id="status" style="font-size:11px; color:gray; text-align:center; margin-top:5px;">대기 중...</p>
|
| 100 |
+
<script>
|
| 101 |
+
const btn = document.getElementById('stt-btn');
|
| 102 |
+
const status = document.getElementById('status');
|
| 103 |
+
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
|
| 104 |
+
recognition.lang = 'ko-KR';
|
| 105 |
+
let isRecognizing = false;
|
| 106 |
+
btn.onclick = () => { if (!isRecognizing) recognition.start(); else recognition.stop(); };
|
| 107 |
+
recognition.onstart = () => { isRecognizing = true; status.innerText = "듣는 중..."; btn.style.backgroundColor = "#ff4b4b"; btn.style.color = "white"; btn.innerHTML = "🛑 음성 입력 중지"; };
|
| 108 |
+
recognition.onresult = (event) => {
|
| 109 |
+
const text = event.results[0][0].transcript;
|
| 110 |
+
const textArea = window.parent.document.querySelector('textarea[aria-label="의견을 입력하세요"]');
|
| 111 |
+
if (textArea) {
|
| 112 |
+
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
|
| 113 |
+
nativeInputValueSetter.call(textArea, textArea.value + " " + text);
|
| 114 |
+
textArea.dispatchEvent(new Event('input', { bubbles: true }));
|
| 115 |
+
status.innerText = "입력 완료!";
|
| 116 |
+
}
|
| 117 |
+
};
|
| 118 |
+
recognition.onend = () => { isRecognizing = false; setTimeout(() => { status.innerText = "대기 중..."; btn.style.backgroundColor = "#e8f0fe"; btn.style.color = "#1a73e8"; btn.innerHTML = "🎤 음성 입력 시작"; }, 1500); };
|
| 119 |
+
</script>
|
| 120 |
+
""",
|
| 121 |
+
height=120,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
if st.button("의견 제출", use_container_width=True, type="primary"):
|
| 125 |
+
input_ok, safe_input, input_error_code, input_error_message = validate_opinion_content(user_input, max_len=700)
|
| 126 |
+
student_ok, safe_student_name, student_error_code, student_error_message = validate_student_name(student_name, max_len=MAX_STUDENT_NAME_LEN)
|
| 127 |
+
student_number_ok, safe_student_number, _, student_number_error_message = validate_student_name(student_number, max_len=20)
|
| 128 |
+
if not student_number_ok and user_role == "학생":
|
| 129 |
+
st.error(f"❌ {student_number_error_message}")
|
| 130 |
+
st.stop()
|
| 131 |
+
if user_role == "학생" and (not safe_student_name or safe_student_name == "익명"):
|
| 132 |
+
safe_student_name = safe_student_number or "학번미입력"
|
| 133 |
+
if input_ok and safe_input:
|
| 134 |
+
now = get_kst_now_str()
|
| 135 |
+
author_role_for_submit = "교사" if user_role == "교사" else "학생"
|
| 136 |
+
client_ip = get_client_ip()
|
| 137 |
+
insert_payload = {
|
| 138 |
+
"room_name": room_name, "timestamp": now, "student_name": safe_student_name,
|
| 139 |
+
"content": safe_input, "sentiment": sentiment, "author_role": author_role_for_submit,
|
| 140 |
+
}
|
| 141 |
+
if debate_ip_column_available() and client_ip:
|
| 142 |
+
insert_payload["ip_address"] = client_ip
|
| 143 |
+
try:
|
| 144 |
+
res = submit_opinion(supabase, insert_payload)
|
| 145 |
+
if res is None:
|
| 146 |
+
st.stop()
|
| 147 |
+
log_audit(
|
| 148 |
+
"opinion_submitted",
|
| 149 |
+
room_name=room_name, actor_name=safe_student_name,
|
| 150 |
+
role=author_role_for_submit, sentiment=sentiment,
|
| 151 |
+
client_ip=client_ip if client_ip else "N/A",
|
| 152 |
+
)
|
| 153 |
+
st.session_state['reset_key'] += 1
|
| 154 |
+
st.rerun()
|
| 155 |
+
except Exception as e:
|
| 156 |
+
st.error(f"저장 실패: {e}")
|
| 157 |
+
else:
|
| 158 |
+
st.warning(f"{input_error_message} ({input_error_code})")
|
| 159 |
+
|
| 160 |
+
st.divider()
|
| 161 |
+
|
| 162 |
+
render_chat_board(supabase, room_name, user_role, teacher_auth, student_name, current_mode, act_type)
|
| 163 |
+
|
| 164 |
+
if user_role == "교사" and teacher_auth:
|
| 165 |
+
render_teacher_dashboard(supabase, room_name, user_role, student_name, current_topic, current_mode, act_type)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import plotly.express as px
|
| 3 |
+
from db import fetch_live_messages, delete_opinion_message
|
| 4 |
+
from validators import with_fallback_author_role, mask_ip_for_teacher
|
| 5 |
+
from utils import format_kst_datetime, log_audit
|
| 6 |
+
from wordcloud import build_word_frequencies, build_circular_wordcloud_html
|
| 7 |
+
from config import DASHBOARD_FETCH_LIMIT, LIVE_BOARD_FETCH_LIMIT, LIVE_REFRESH_INTERVAL, UI_FONT_FAMILY
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _live_chat_board_core(supabase, room_name, user_role, teacher_auth, student_name, current_mode, act_type):
|
| 11 |
+
all_df = with_fallback_author_role(
|
| 12 |
+
fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT)
|
| 13 |
+
)
|
| 14 |
+
opinion_df = all_df.head(LIVE_BOARD_FETCH_LIMIT) if not all_df.empty else all_df
|
| 15 |
+
stats_opinion_df = all_df
|
| 16 |
+
|
| 17 |
+
with st.expander("📊 실시간 의견 통계 보기 (클릭하여 펼치기)"):
|
| 18 |
+
if not stats_opinion_df.empty:
|
| 19 |
+
left_col, right_col = st.columns(2)
|
| 20 |
+
with left_col:
|
| 21 |
+
st.caption("감정 분포 그래프")
|
| 22 |
+
live_pie_fig = px.pie(stats_opinion_df, names="sentiment", hole=0.4, height=320)
|
| 23 |
+
live_pie_fig.update_layout(font={"family": UI_FONT_FAMILY})
|
| 24 |
+
st.plotly_chart(live_pie_fig, use_container_width=True, config={'displayModeBar': False, 'scrollZoom': False})
|
| 25 |
+
with right_col:
|
| 26 |
+
st.caption("누적 토의/토론 워드클라우드")
|
| 27 |
+
frequencies = build_word_frequencies(stats_opinion_df["content"])
|
| 28 |
+
if frequencies:
|
| 29 |
+
st.markdown(build_circular_wordcloud_html(frequencies), unsafe_allow_html=True)
|
| 30 |
+
top_words = ", ".join([f"{word}({count})" for word, count in frequencies.most_common(8)])
|
| 31 |
+
st.caption(f"상위 키워드: {top_words}")
|
| 32 |
+
else:
|
| 33 |
+
st.info("워드클라우드를 만들 단어가 아직 부족합니다.")
|
| 34 |
+
else:
|
| 35 |
+
st.write("데이터 수집 중...")
|
| 36 |
+
|
| 37 |
+
col_board_title, col_board_ref = st.columns([8, 2])
|
| 38 |
+
with col_board_title:
|
| 39 |
+
st.subheader(f"💬 실시간 {act_type} 보드")
|
| 40 |
+
with col_board_ref:
|
| 41 |
+
if user_role == "교사" and teacher_auth:
|
| 42 |
+
st.button("🔄 실시간 보드 새로고침", use_container_width=True, key="refresh_chat_board")
|
| 43 |
+
|
| 44 |
+
if not opinion_df.empty:
|
| 45 |
+
teacher_df = opinion_df[opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 46 |
+
if not teacher_df.empty:
|
| 47 |
+
st.success(f"👨🏫 **선생님의 생각 힌트!** ➡️ {teacher_df.iloc[0]['content']}")
|
| 48 |
+
|
| 49 |
+
student_df = opinion_df[~opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 50 |
+
|
| 51 |
+
def delete_chat_msg(msg_id):
|
| 52 |
+
try:
|
| 53 |
+
if delete_opinion_message(supabase, msg_id) is None:
|
| 54 |
+
return
|
| 55 |
+
log_audit("chat_deleted", room_name=room_name, actor_name=student_name, role=user_role, message_id=msg_id)
|
| 56 |
+
st.toast("의견이 즉시 삭제되었습니다.", icon="🗑️")
|
| 57 |
+
except Exception as e:
|
| 58 |
+
st.error(f"삭제 실패: {e}")
|
| 59 |
+
|
| 60 |
+
def render_msg(row):
|
| 61 |
+
formatted_timestamp = format_kst_datetime(row.get("timestamp", ""))
|
| 62 |
+
if user_role == "교사" and teacher_auth:
|
| 63 |
+
c_name, c_btn = st.columns([5, 1])
|
| 64 |
+
with c_name:
|
| 65 |
+
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 66 |
+
row_ip = str(row.get("ip_address", "")).strip() if hasattr(row, "get") else ""
|
| 67 |
+
if row_ip:
|
| 68 |
+
st.caption(f"IP: {mask_ip_for_teacher(row_ip)}")
|
| 69 |
+
with c_btn:
|
| 70 |
+
st.button("❌", key=f"del_{row['id']}", help="강제 삭제", on_click=delete_chat_msg, args=(row['id'],))
|
| 71 |
+
st.info(row['content'])
|
| 72 |
+
else:
|
| 73 |
+
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 74 |
+
st.info(row['content'])
|
| 75 |
+
st.write("")
|
| 76 |
+
|
| 77 |
+
if current_mode == "⚔️ 찬반 토론":
|
| 78 |
+
col_pro, col_con = st.columns(2)
|
| 79 |
+
with col_pro:
|
| 80 |
+
st.markdown("### 🔵 찬성 측")
|
| 81 |
+
with st.container(height=450):
|
| 82 |
+
for _, row in student_df[student_df['sentiment'] == '🔵 찬성'].iterrows():
|
| 83 |
+
render_msg(row)
|
| 84 |
+
with col_con:
|
| 85 |
+
st.markdown("### 🔴 반대 측")
|
| 86 |
+
with st.container(height=450):
|
| 87 |
+
for _, row in student_df[student_df['sentiment'] == '🔴 반대'].iterrows():
|
| 88 |
+
render_msg(row)
|
| 89 |
+
else:
|
| 90 |
+
col_idea, col_plus, col_q = st.columns(3)
|
| 91 |
+
with col_idea:
|
| 92 |
+
st.markdown("### 💡 아이디어")
|
| 93 |
+
with st.container(height=450):
|
| 94 |
+
for _, row in student_df[student_df['sentiment'] == '💡 아이디어'].iterrows():
|
| 95 |
+
render_msg(row)
|
| 96 |
+
with col_plus:
|
| 97 |
+
st.markdown("### ➕ 보충")
|
| 98 |
+
with st.container(height=450):
|
| 99 |
+
for _, row in student_df[student_df['sentiment'] == '➕ 보충'].iterrows():
|
| 100 |
+
render_msg(row)
|
| 101 |
+
with col_q:
|
| 102 |
+
st.markdown("### ❓ 질문")
|
| 103 |
+
with st.container(height=450):
|
| 104 |
+
for _, row in student_df[student_df['sentiment'] == '❓ 질문'].iterrows():
|
| 105 |
+
render_msg(row)
|
| 106 |
+
else:
|
| 107 |
+
st.info(f"아직 대화가 없습니다. 첫 {act_type} 의견을 남겨주세요!")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@st.fragment(run_every=LIVE_REFRESH_INTERVAL)
|
| 111 |
+
def _live_chat_board_auto(supabase, room_name, user_role, teacher_auth, student_name, current_mode, act_type):
|
| 112 |
+
_live_chat_board_core(supabase, room_name, user_role, teacher_auth, student_name, current_mode, act_type)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def render_chat_board(supabase, room_name, user_role, teacher_auth, student_name, current_mode, act_type):
|
| 116 |
+
if st.session_state.get('is_working', False):
|
| 117 |
+
_live_chat_board_core(supabase, room_name, user_role, teacher_auth, student_name, current_mode, act_type)
|
| 118 |
+
else:
|
| 119 |
+
_live_chat_board_auto(supabase, room_name, user_role, teacher_auth, student_name, current_mode, act_type)
|
components/sidebar.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from db import (
|
| 3 |
+
fetch_room_names,
|
| 4 |
+
fetch_room_names_by_owner,
|
| 5 |
+
fetch_teacher_account,
|
| 6 |
+
request_teacher_account,
|
| 7 |
+
topic_owner_column_available,
|
| 8 |
+
topic_entry_code_column_available,
|
| 9 |
+
upsert_topic_room,
|
| 10 |
+
using_service_role_key,
|
| 11 |
+
_get_secret,
|
| 12 |
+
)
|
| 13 |
+
from validators import (
|
| 14 |
+
normalize_user_text,
|
| 15 |
+
validate_entry_code,
|
| 16 |
+
validate_opinion_content,
|
| 17 |
+
validate_room_name,
|
| 18 |
+
validate_teacher_credential,
|
| 19 |
+
)
|
| 20 |
+
from utils import log_audit, to_bool_flag
|
| 21 |
+
from config import MAX_ROOM_NAME_LEN, MAX_TOPIC_LEN, MAX_ENTRY_CODE_LEN
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def reset_joined_state():
|
| 25 |
+
st.session_state['joined'] = False
|
| 26 |
+
st.session_state['teacher_auth'] = False
|
| 27 |
+
st.session_state['admin_auth'] = False
|
| 28 |
+
st.session_state['teacher_id'] = ""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def redirect_from_admin_page_if_needed():
|
| 32 |
+
if st.session_state.get('page') == "admin_approval" and not st.session_state.get('admin_auth', False):
|
| 33 |
+
st.session_state['page'] = "lobby"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def render_sidebar(supabase) -> dict:
|
| 37 |
+
with st.sidebar:
|
| 38 |
+
st.header("👤 접속 권한")
|
| 39 |
+
user_role = st.radio("모드 선택", ["학생", "교사"], on_change=reset_joined_state)
|
| 40 |
+
st.divider()
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
all_rooms = fetch_room_names(supabase)
|
| 44 |
+
except Exception:
|
| 45 |
+
all_rooms = []
|
| 46 |
+
|
| 47 |
+
room_name = ""
|
| 48 |
+
teacher_auth = False
|
| 49 |
+
admin_auth = False
|
| 50 |
+
student_number = ""
|
| 51 |
+
teacher_id_for_scope = st.session_state.get("teacher_id", "")
|
| 52 |
+
|
| 53 |
+
if user_role == "교사":
|
| 54 |
+
auth_mode = st.radio("교사 계정", ["로그인", "ID/PW 신청"], horizontal=True)
|
| 55 |
+
|
| 56 |
+
if auth_mode == "로그인":
|
| 57 |
+
with st.form("teacher_login_form"):
|
| 58 |
+
teacher_id_input = st.text_input("교사 ID", key="teacher_id_input")
|
| 59 |
+
teacher_pw_input = st.text_input("교사 PW", type="password", key="teacher_pw_input")
|
| 60 |
+
login_submitted = st.form_submit_button("교사 로그인", use_container_width=True)
|
| 61 |
+
|
| 62 |
+
if login_submitted:
|
| 63 |
+
id_ok, safe_teacher_id, id_error_code, id_error_message = validate_teacher_credential(teacher_id_input, field_name="교사 ID", max_len=60)
|
| 64 |
+
pw_ok, safe_pw, pw_error_code, pw_error_message = validate_teacher_credential(teacher_pw_input, field_name="교사 PW", max_len=60)
|
| 65 |
+
if not id_ok:
|
| 66 |
+
st.error(f"❌ {id_error_message} ({id_error_code})")
|
| 67 |
+
st.stop()
|
| 68 |
+
if not pw_ok:
|
| 69 |
+
st.error(f"❌ {pw_error_message} ({pw_error_code})")
|
| 70 |
+
st.stop()
|
| 71 |
+
account = fetch_teacher_account(supabase, safe_teacher_id)
|
| 72 |
+
if isinstance(account, dict) and account.get("_query_failed"):
|
| 73 |
+
st.session_state['teacher_auth'] = False
|
| 74 |
+
st.session_state['admin_auth'] = False
|
| 75 |
+
st.session_state['teacher_id'] = ""
|
| 76 |
+
redirect_from_admin_page_if_needed()
|
| 77 |
+
st.error("🚨 교사 계정 조회에 실패했습니다. Supabase RLS 정책/권한 및 DB 연결 상태를 확인해 주세요.")
|
| 78 |
+
elif not account:
|
| 79 |
+
st.session_state['teacher_auth'] = False
|
| 80 |
+
st.session_state['admin_auth'] = False
|
| 81 |
+
st.session_state['teacher_id'] = ""
|
| 82 |
+
redirect_from_admin_page_if_needed()
|
| 83 |
+
st.error("🚨 등록되지 않은 교사 ID입니다.")
|
| 84 |
+
if not using_service_role_key():
|
| 85 |
+
st.warning(
|
| 86 |
+
"⚠️ 현재 앱이 SERVICE ROLE KEY 없이 동작 중입니다. "
|
| 87 |
+
"teacher_accounts 테이블에 RLS 정책이 없으면 Data API 조회 결과가 0건으로 나와 "
|
| 88 |
+
"등록된 계정도 미등록으로 보일 수 있습니다."
|
| 89 |
+
)
|
| 90 |
+
try:
|
| 91 |
+
supabase_url = str(_get_secret("SUPABASE_URL", ""))
|
| 92 |
+
project_ref = supabase_url.split("//", 1)[-1].split(".", 1)[0] if supabase_url else ""
|
| 93 |
+
if project_ref:
|
| 94 |
+
st.caption(f"현재 앱 연결 DB 프로젝트: `{project_ref}`")
|
| 95 |
+
except Exception:
|
| 96 |
+
pass
|
| 97 |
+
elif account.get("teacher_pw") != safe_pw:
|
| 98 |
+
st.session_state['teacher_auth'] = False
|
| 99 |
+
st.session_state['admin_auth'] = False
|
| 100 |
+
st.session_state['teacher_id'] = ""
|
| 101 |
+
redirect_from_admin_page_if_needed()
|
| 102 |
+
st.error("❌ 비밀번호가 일치하지 않습니다.")
|
| 103 |
+
elif not account.get("is_approved"):
|
| 104 |
+
st.session_state['teacher_auth'] = False
|
| 105 |
+
st.session_state['admin_auth'] = False
|
| 106 |
+
st.session_state['teacher_id'] = ""
|
| 107 |
+
redirect_from_admin_page_if_needed()
|
| 108 |
+
st.warning("⏳ 최고관리자 승인 후 로그인할 수 있습니다.")
|
| 109 |
+
else:
|
| 110 |
+
st.session_state['teacher_auth'] = True
|
| 111 |
+
st.session_state['admin_auth'] = to_bool_flag(account.get("is_admin", False))
|
| 112 |
+
st.session_state['teacher_id'] = safe_teacher_id
|
| 113 |
+
redirect_from_admin_page_if_needed()
|
| 114 |
+
if st.session_state['admin_auth']:
|
| 115 |
+
st.session_state['page'] = "admin_approval"
|
| 116 |
+
st.toast("✅ 관리자 계정 로그인 성공", icon="✅")
|
| 117 |
+
st.rerun()
|
| 118 |
+
else:
|
| 119 |
+
st.toast("✅ 교사 로그인 성공", icon="✅")
|
| 120 |
+
else:
|
| 121 |
+
req_teacher_id = st.text_input("신청할 교사 ID", key="req_teacher_id")
|
| 122 |
+
req_teacher_pw = st.text_input("신청할 교사 PW", type="password", key="req_teacher_pw")
|
| 123 |
+
if st.button("교사 계정 신청", type="primary", use_container_width=True):
|
| 124 |
+
id_ok, safe_id, id_error_code, id_error_message = validate_teacher_credential(req_teacher_id, field_name="교사 ID", max_len=60)
|
| 125 |
+
pw_ok, safe_pw, pw_error_code, pw_error_message = validate_teacher_credential(req_teacher_pw, field_name="교사 PW", max_len=60)
|
| 126 |
+
if not id_ok:
|
| 127 |
+
st.error(f"❌ {id_error_message} ({id_error_code})")
|
| 128 |
+
elif not pw_ok:
|
| 129 |
+
st.error(f"❌ {pw_error_message} ({pw_error_code})")
|
| 130 |
+
elif fetch_teacher_account(supabase, safe_id):
|
| 131 |
+
st.warning("이미 존재하는 ID입니다. 다른 ID를 사용해 주세요.")
|
| 132 |
+
else:
|
| 133 |
+
req_res = request_teacher_account(supabase, safe_id, safe_pw)
|
| 134 |
+
if req_res is not None:
|
| 135 |
+
st.success("신청 완료! 최고관리자 승인 후 로그인할 수 있습니다.")
|
| 136 |
+
|
| 137 |
+
teacher_auth = st.session_state['teacher_auth']
|
| 138 |
+
admin_auth = st.session_state['admin_auth']
|
| 139 |
+
teacher_id_for_scope = st.session_state.get("teacher_id", "")
|
| 140 |
+
|
| 141 |
+
if teacher_auth:
|
| 142 |
+
st.caption(f"🔐 {teacher_id_for_scope} 로그인 중")
|
| 143 |
+
if st.button("🚪 로그아웃", use_container_width=True):
|
| 144 |
+
st.session_state['teacher_auth'] = False
|
| 145 |
+
st.session_state['admin_auth'] = False
|
| 146 |
+
st.session_state['teacher_id'] = ""
|
| 147 |
+
st.session_state['joined'] = False
|
| 148 |
+
st.session_state['page'] = "lobby"
|
| 149 |
+
st.rerun()
|
| 150 |
+
st.divider()
|
| 151 |
+
|
| 152 |
+
if teacher_auth and admin_auth:
|
| 153 |
+
st.caption("관리자 바로가기")
|
| 154 |
+
if st.button("📝 ID 요청 수락", use_container_width=True):
|
| 155 |
+
st.session_state['page'] = "admin_approval"
|
| 156 |
+
st.rerun()
|
| 157 |
+
if st.button("🚪 말자취(Talk-Trace) AI 대기실", use_container_width=True):
|
| 158 |
+
st.session_state['page'] = "lobby"
|
| 159 |
+
st.rerun()
|
| 160 |
+
st.divider()
|
| 161 |
+
|
| 162 |
+
if teacher_auth:
|
| 163 |
+
existing_rooms = all_rooms if admin_auth else (
|
| 164 |
+
fetch_room_names_by_owner(supabase, teacher_id_for_scope)
|
| 165 |
+
if topic_owner_column_available()
|
| 166 |
+
else []
|
| 167 |
+
)
|
| 168 |
+
if not admin_auth and not topic_owner_column_available():
|
| 169 |
+
st.warning("교사별 방 조회를 위해 topic.created_by_teacher_id(권장) 또는 topic.created_by 컬럼이 필요합니다.")
|
| 170 |
+
|
| 171 |
+
room_opt = st.radio("방 관리", ["기존 방 선택", "새 방 만들기"])
|
| 172 |
+
if room_opt == "기존 방 선택" and existing_rooms:
|
| 173 |
+
room_name = st.selectbox("토론/토의방 목록", existing_rooms)
|
| 174 |
+
else:
|
| 175 |
+
new_room = st.text_input("새로 만들 방 이름 (예: 1학년 3반)")
|
| 176 |
+
new_title = st.text_input("주제 직접 입력 (예: 인공지능 윤리)")
|
| 177 |
+
new_mode = st.radio("진행 방식", ["⚔️ 찬반 토론", "💡 자유 토의"], horizontal=True)
|
| 178 |
+
new_pw = st.text_input("🔒 학생 입장용 암호 (비워두면 공개방)")
|
| 179 |
+
if st.button("새 방 개설하기", type="primary"):
|
| 180 |
+
room_ok, safe_new_room, room_error_code, room_error_message = validate_room_name(new_room, max_len=MAX_ROOM_NAME_LEN)
|
| 181 |
+
title_ok, safe_new_title, title_error_code, title_error_message = validate_opinion_content(new_title, max_len=MAX_TOPIC_LEN)
|
| 182 |
+
entry_ok, safe_new_pw, entry_error_code, entry_error_message = validate_entry_code(new_pw, max_len=MAX_ENTRY_CODE_LEN)
|
| 183 |
+
can_store_room_pw = topic_entry_code_column_available()
|
| 184 |
+
if not room_ok:
|
| 185 |
+
st.error(f"❌ {room_error_message} ({room_error_code})")
|
| 186 |
+
elif not title_ok:
|
| 187 |
+
st.error(f"❌ {title_error_message} ({title_error_code})")
|
| 188 |
+
elif not entry_ok:
|
| 189 |
+
st.error(f"❌ {entry_error_message} ({entry_error_code})")
|
| 190 |
+
elif safe_new_pw and not can_store_room_pw:
|
| 191 |
+
st.error("현재 DB 구조에서는 방 비밀번호 저장을 지원하지 않습니다.")
|
| 192 |
+
elif safe_new_room and safe_new_title:
|
| 193 |
+
res = upsert_topic_room(
|
| 194 |
+
supabase=supabase, room_name=safe_new_room, title=safe_new_title,
|
| 195 |
+
mode=new_mode, entry_code=safe_new_pw, created_by=teacher_id_for_scope,
|
| 196 |
+
)
|
| 197 |
+
if res is not None:
|
| 198 |
+
st.success(f"'{safe_new_room}' 방이 개설되었습니다! '기존 방 선택'을 눌러 입장하세요.")
|
| 199 |
+
room_name = ""
|
| 200 |
+
else:
|
| 201 |
+
st.session_state['teacher_auth'] = False
|
| 202 |
+
st.session_state['admin_auth'] = False
|
| 203 |
+
st.session_state['teacher_id'] = ""
|
| 204 |
+
redirect_from_admin_page_if_needed()
|
| 205 |
+
student_number = st.text_input("학번", key="student_number_input", placeholder="예: 1101")
|
| 206 |
+
if all_rooms:
|
| 207 |
+
room_name = st.selectbox("🏠 접속할 방 선택", all_rooms)
|
| 208 |
+
else:
|
| 209 |
+
st.warning("선생님이 아직 열어둔 방이 없습니다.")
|
| 210 |
+
room_name = ""
|
| 211 |
+
|
| 212 |
+
student_name = normalize_user_text(student_number, max_len=20) if user_role == "학생" else "교사"
|
| 213 |
+
|
| 214 |
+
if room_name and room_name != st.session_state['current_room']:
|
| 215 |
+
prev_room = st.session_state['current_room']
|
| 216 |
+
st.session_state['current_room'] = room_name
|
| 217 |
+
st.session_state['ai_hint_text'] = ""
|
| 218 |
+
st.session_state['ai_report_text'] = ""
|
| 219 |
+
st.session_state['ai_result_text'] = ""
|
| 220 |
+
if st.session_state['joined']:
|
| 221 |
+
st.session_state['joined'] = False
|
| 222 |
+
log_audit("room_switched_to_lobby", room_name=room_name, actor_name=student_name, role=user_role, previous_room=prev_room)
|
| 223 |
+
st.rerun()
|
| 224 |
+
|
| 225 |
+
if st.session_state['joined']:
|
| 226 |
+
st.divider()
|
| 227 |
+
if st.button("🚪 방 나가기 (대기실로)"):
|
| 228 |
+
st.session_state['joined'] = False
|
| 229 |
+
st.rerun()
|
| 230 |
+
|
| 231 |
+
return {
|
| 232 |
+
'user_role': user_role,
|
| 233 |
+
'room_name': room_name,
|
| 234 |
+
'teacher_auth': teacher_auth,
|
| 235 |
+
'admin_auth': admin_auth,
|
| 236 |
+
'student_name': student_name,
|
| 237 |
+
'student_number': student_number,
|
| 238 |
+
}
|
components/teacher_dashboard.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import html
|
| 2 |
+
import io
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import plotly.express as px
|
| 7 |
+
import streamlit as st
|
| 8 |
+
|
| 9 |
+
from db import (
|
| 10 |
+
create_teacher_hint,
|
| 11 |
+
delete_student_record,
|
| 12 |
+
destroy_room_data,
|
| 13 |
+
fetch_live_messages,
|
| 14 |
+
fetch_student_records,
|
| 15 |
+
save_student_record,
|
| 16 |
+
_get_secret,
|
| 17 |
+
)
|
| 18 |
+
from services.ai import generate_ai_response
|
| 19 |
+
from validators import with_fallback_author_role
|
| 20 |
+
from utils import compact_ai_report_output, get_kst_now, get_kst_now_str, log_audit
|
| 21 |
+
from config import (
|
| 22 |
+
AI_MODEL_NAME,
|
| 23 |
+
AI_HINT_ENABLED,
|
| 24 |
+
DASHBOARD_FETCH_LIMIT,
|
| 25 |
+
RECORDS_FETCH_LIMIT,
|
| 26 |
+
ROOM_DESTROY_ENABLED,
|
| 27 |
+
UI_FONT_FAMILY,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
logger = logging.getLogger("talk_trace_ai")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def render_teacher_dashboard(supabase, room_name, user_role, student_name, current_topic, current_mode, act_type):
|
| 34 |
+
st.divider()
|
| 35 |
+
col_dash_title, col_dash_refresh = st.columns([8, 2])
|
| 36 |
+
with col_dash_title:
|
| 37 |
+
st.header("👨🏫 교사 관리 대시보드")
|
| 38 |
+
with col_dash_refresh:
|
| 39 |
+
if st.button("🔄 대시보드 수동 새로고침", use_container_width=True):
|
| 40 |
+
st.rerun()
|
| 41 |
+
|
| 42 |
+
df_all = with_fallback_author_role(fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT))
|
| 43 |
+
student_only_df = (
|
| 44 |
+
df_all[
|
| 45 |
+
(df_all['author_role'] == '학생') &
|
| 46 |
+
~df_all['student_name'].str.contains('익명|AI', na=False, regex=True)
|
| 47 |
+
].copy()
|
| 48 |
+
if not df_all.empty else df_all
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
st.subheader("📊 학생 참여도 현황")
|
| 52 |
+
if not df_all.empty:
|
| 53 |
+
if not student_only_df.empty:
|
| 54 |
+
counts = student_only_df['student_name'].astype(str).value_counts().reset_index()
|
| 55 |
+
counts.columns = ['학생 이름', '참여 횟수']
|
| 56 |
+
counts['학생 이름'] = counts['학생 이름'] + " "
|
| 57 |
+
fig = px.bar(counts, x='학생 이름', y='참여 횟수', text='참여 횟수', color='학생 이름')
|
| 58 |
+
fig.update_xaxes(type='category', title="")
|
| 59 |
+
fig.update_layout(yaxis_title="의견 수", dragmode=False, showlegend=False, font={"family": UI_FONT_FAMILY})
|
| 60 |
+
st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': False, 'displayModeBar': False})
|
| 61 |
+
else:
|
| 62 |
+
st.info("실명 참여 데이터가 없습니다.")
|
| 63 |
+
else:
|
| 64 |
+
st.info(f"{act_type} 데이터가 없습니다.")
|
| 65 |
+
|
| 66 |
+
st.divider()
|
| 67 |
+
|
| 68 |
+
@st.fragment
|
| 69 |
+
def teacher_hint_section():
|
| 70 |
+
st.subheader(f"💡 AI {act_type} 촉진 (Teacher-in-the-loop)")
|
| 71 |
+
st.info("AI 제안을 수정 후 전송하세요.")
|
| 72 |
+
|
| 73 |
+
def send_hint():
|
| 74 |
+
val = st.session_state.get('hint_input_widget', '').strip()
|
| 75 |
+
if val:
|
| 76 |
+
now = get_kst_now_str()
|
| 77 |
+
try:
|
| 78 |
+
res = create_teacher_hint(supabase, {
|
| 79 |
+
"room_name": room_name, "timestamp": now,
|
| 80 |
+
"student_name": "👨🏫 선생님 (AI 보조)",
|
| 81 |
+
"content": val, "sentiment": "❓ 질문", "author_role": "교사"
|
| 82 |
+
})
|
| 83 |
+
if res is None:
|
| 84 |
+
return
|
| 85 |
+
log_audit("teacher_hint_sent", room_name=room_name, actor_name=student_name, role=user_role)
|
| 86 |
+
st.session_state['hint_input_widget'] = ""
|
| 87 |
+
except Exception as e:
|
| 88 |
+
st.error(f"힌트 전송 실패: {e}")
|
| 89 |
+
|
| 90 |
+
if AI_HINT_ENABLED:
|
| 91 |
+
if st.button("🪄 AI 힌트 초안 생성", use_container_width=True):
|
| 92 |
+
st.toast("👀 AI가 대화 맥락을 읽고 있습니다...", icon="⏳")
|
| 93 |
+
with st.spinner("✍️ 예리한 질문을 작성하고 있습니다..."):
|
| 94 |
+
context = "\n".join(df_all['content'].tail(5).tolist()) if not df_all.empty else "대화 없음"
|
| 95 |
+
prompt = (
|
| 96 |
+
f"당신은 고등학교 {act_type} 조력자입니다. '{current_topic}' 주제로 {act_type} 중입니다. "
|
| 97 |
+
"학생들의 균형을 맞추거나 더 깊은 생각을 유도할 수 있는 예리한 질문을 1문장만 제안하세요. "
|
| 98 |
+
f"번호 매기기나 번잡한 서론 없이 질문 자체만 출력하세요.\n최근 대화: {context}"
|
| 99 |
+
)
|
| 100 |
+
res_text = generate_ai_response(
|
| 101 |
+
prompt, model_name=AI_MODEL_NAME, api_key=_get_secret("GEMINI_API_KEY", ""),
|
| 102 |
+
log_message="AI 힌트 생성 실패", room_name=room_name,
|
| 103 |
+
)
|
| 104 |
+
if res_text:
|
| 105 |
+
st.session_state['hint_input_widget'] = res_text.strip().split('\n')[0]
|
| 106 |
+
st.session_state['ai_hint_manual_mode'] = False
|
| 107 |
+
st.toast("✅ 힌트 작성 완료!", icon="🎉")
|
| 108 |
+
else:
|
| 109 |
+
st.session_state['ai_hint_manual_mode'] = True
|
| 110 |
+
st.toast("🚨 AI 호출 오류: 수동 모드로 전환되었습니다.", icon="❌")
|
| 111 |
+
else:
|
| 112 |
+
st.session_state['ai_hint_manual_mode'] = True
|
| 113 |
+
|
| 114 |
+
col_edit_txt, col_edit_btn = st.columns([8, 2])
|
| 115 |
+
with col_edit_txt:
|
| 116 |
+
st.text_input("선생님의 검토 및 수정", key="hint_input_widget", label_visibility="collapsed", placeholder="여기에 AI 힌트가 나타납니다.")
|
| 117 |
+
with col_edit_btn:
|
| 118 |
+
st.button("🚀 학생 화면 전송", use_container_width=True, type="primary", on_click=send_hint)
|
| 119 |
+
|
| 120 |
+
teacher_hint_section()
|
| 121 |
+
st.divider()
|
| 122 |
+
|
| 123 |
+
@st.fragment
|
| 124 |
+
def teacher_summary_section():
|
| 125 |
+
st.subheader(f"📝 수업 종료 및 전체 {act_type} 요약 리포트")
|
| 126 |
+
if st.button(f"{act_type} 요약 및 베스트 발언 추출 🪄", use_container_width=True):
|
| 127 |
+
st.toast("👀 AI가 전체 기록을 꼼꼼히 읽고 있습니다...", icon="⏳")
|
| 128 |
+
with st.spinner("✍️ 요약 리포트를 작성하고 있습니다..."):
|
| 129 |
+
if not df_all.empty:
|
| 130 |
+
full_history = "\n".join([
|
| 131 |
+
f"[{row['student_name']} - {row['sentiment']}] {row['content']}"
|
| 132 |
+
for _, row in df_all.iterrows()
|
| 133 |
+
])
|
| 134 |
+
prompt = (
|
| 135 |
+
f"'{current_topic}' 주제의 고등학교 {act_type} 기록입니다.\n\n"
|
| 136 |
+
"[출력 형식 - 반드시 그대로]\n"
|
| 137 |
+
"핵심요약 1: ...\n핵심요약 2: ...\n핵심요약 3: ...\n베스트 학생: ...\n선정 이유: ...\n\n"
|
| 138 |
+
"[엄격한 규칙]\n"
|
| 139 |
+
"- 핵심요약 1,2,3과 베스트 학생, 선정이유를 줄바꿈을 하여 보기 편하게 합니다.\n"
|
| 140 |
+
"- 5~10줄로 출력합니다.\n- 제목/헤더(#,##,###), 소제목을 절대 쓰지 않습니다.\n"
|
| 141 |
+
"- 불필요한 서론/결론 없이 바로 결과만 출력합니다.\n\n"
|
| 142 |
+
f"기록:\n{full_history}"
|
| 143 |
+
)
|
| 144 |
+
res_text = generate_ai_response(
|
| 145 |
+
prompt, model_name=AI_MODEL_NAME, api_key=_get_secret("GEMINI_API_KEY", ""),
|
| 146 |
+
log_message="AI 요약 리포트 생성 실패", room_name=room_name,
|
| 147 |
+
)
|
| 148 |
+
if res_text:
|
| 149 |
+
st.session_state['ai_report_text'] = compact_ai_report_output(res_text)
|
| 150 |
+
st.toast("✅ 리포트 작성 완료!", icon="🎉")
|
| 151 |
+
else:
|
| 152 |
+
st.toast("🚨 AI 호출 오류가 발생했습니다.", icon="❌")
|
| 153 |
+
else:
|
| 154 |
+
st.toast("🚨 분석할 데이터가 없습니다.", icon="⚠️")
|
| 155 |
+
if st.session_state.get('ai_report_text'):
|
| 156 |
+
st.info(f"📊 **AI 수업 {act_type} 요약 리포트**")
|
| 157 |
+
report_html = html.escape(st.session_state['ai_report_text']).replace("\n", "<br>")
|
| 158 |
+
st.markdown(f"<div style='line-height:1.8;'>{report_html}</div>", unsafe_allow_html=True)
|
| 159 |
+
|
| 160 |
+
teacher_summary_section()
|
| 161 |
+
st.divider()
|
| 162 |
+
|
| 163 |
+
@st.fragment
|
| 164 |
+
def teacher_record_section():
|
| 165 |
+
def delete_selected_record():
|
| 166 |
+
del_id = st.session_state.get('del_record_dropdown')
|
| 167 |
+
if del_id:
|
| 168 |
+
try:
|
| 169 |
+
if delete_student_record(supabase, del_id) is None:
|
| 170 |
+
return
|
| 171 |
+
log_audit("record_deleted", room_name=room_name, actor_name=student_name, role=user_role, record_id=del_id)
|
| 172 |
+
st.toast("기록이 삭제되었습니다.", icon="🗑️")
|
| 173 |
+
except Exception as e:
|
| 174 |
+
st.error(f"기록 삭제 실패: {e}")
|
| 175 |
+
|
| 176 |
+
col3, col4 = st.columns([1, 1])
|
| 177 |
+
with col3:
|
| 178 |
+
st.subheader("📥 활동 데이터 다운로드")
|
| 179 |
+
if not df_all.empty:
|
| 180 |
+
buffer = io.BytesIO()
|
| 181 |
+
with pd.ExcelWriter(buffer, engine='openpyxl') as writer:
|
| 182 |
+
df_all.to_excel(writer, index=False)
|
| 183 |
+
st.download_button(
|
| 184 |
+
f"{act_type} 전체 활동 로그 (Excel)",
|
| 185 |
+
data=buffer.getvalue(),
|
| 186 |
+
file_name=f"{room_name}_log_{get_kst_now().strftime('%Y%m%d_%H%M')}.xlsx",
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
with col4:
|
| 190 |
+
st.subheader("🤖 개인별 AI 세특 초안 생성")
|
| 191 |
+
student_list = student_only_df['student_name'].unique() if not student_only_df.empty else []
|
| 192 |
+
if len(student_list) > 0:
|
| 193 |
+
selected_student = st.selectbox("학생을 선택하세요", student_list)
|
| 194 |
+
if st.button(f"'{selected_student}' 세특 생성 🪄", use_container_width=True):
|
| 195 |
+
st.toast(f"👀 AI가 '{selected_student}' 학생의 활동을 분석합니다...", icon="⏳")
|
| 196 |
+
with st.spinner(f"✍️ '{selected_student}' 학생의 세특 초안 작성 중..."):
|
| 197 |
+
try:
|
| 198 |
+
student_data = df_all[df_all['student_name'] == selected_student]
|
| 199 |
+
debate_history = "\n".join([f"- [{row['sentiment']}] {row['content']}" for _, row in student_data.iterrows()])
|
| 200 |
+
prompt = (
|
| 201 |
+
f"당신은 정보 교사입니다. '{current_topic}' 주제 {act_type}에 참여한 "
|
| 202 |
+
f"'{selected_student}' 학생의 활동 기록입니다. 이를 바탕으로 생활기록부 "
|
| 203 |
+
f"교과세특 초안을 약 300자 내외로 작성하세요. 교육적 성장을 강조하세요.\n\n"
|
| 204 |
+
f"[활동 기록]\n{debate_history}"
|
| 205 |
+
)
|
| 206 |
+
res_text = generate_ai_response(
|
| 207 |
+
prompt, model_name=AI_MODEL_NAME, api_key=_get_secret("GEMINI_API_KEY", ""),
|
| 208 |
+
log_message="AI 세특 생성 실패", room_name=room_name, student=selected_student,
|
| 209 |
+
)
|
| 210 |
+
if res_text:
|
| 211 |
+
st.session_state['ai_result_text'] = res_text
|
| 212 |
+
now = get_kst_now_str()
|
| 213 |
+
save_res = save_student_record(supabase, {
|
| 214 |
+
"room_name": room_name, "timestamp": now,
|
| 215 |
+
"student_name": selected_student, "content": res_text,
|
| 216 |
+
})
|
| 217 |
+
if save_res is None:
|
| 218 |
+
raise RuntimeError("보관함 저장 실패")
|
| 219 |
+
st.toast("✅ 세특 생성 및 보관함 저장 완료!", icon="🎉")
|
| 220 |
+
else:
|
| 221 |
+
raise RuntimeError("AI 응답 비어있음")
|
| 222 |
+
except Exception:
|
| 223 |
+
logger.exception("세특 생성 후처리 실패")
|
| 224 |
+
st.toast("🚨 오류가 발생했습니다. 다시 시도해주세요.", icon="❌")
|
| 225 |
+
if st.session_state.get('ai_result_text'):
|
| 226 |
+
st.success("🤖 **개인별 세특 초안** (보관함에 자동 저장되었습니다)")
|
| 227 |
+
st.text_area("내용 수정 후 복사하여 사용하세요", value=st.session_state['ai_result_text'], height=200, label_visibility="collapsed")
|
| 228 |
+
else:
|
| 229 |
+
st.info("실명 참여 학생이 없습니다.")
|
| 230 |
+
|
| 231 |
+
st.divider()
|
| 232 |
+
st.subheader("📂 저장된 세특 기록 보관함")
|
| 233 |
+
records_df = fetch_student_records(supabase, room_name, RECORDS_FETCH_LIMIT)
|
| 234 |
+
if not records_df.empty:
|
| 235 |
+
records_display_df = records_df.rename(columns={"id": "No.", "content": "세특 내용"})
|
| 236 |
+
records_html = records_display_df.to_html(index=False, escape=True)
|
| 237 |
+
st.markdown(f"<div class='records-db-table-wrap'>{records_html}</div>", unsafe_allow_html=True)
|
| 238 |
+
col_down, col_del = st.columns([1, 1])
|
| 239 |
+
with col_down:
|
| 240 |
+
buffer_records = io.BytesIO()
|
| 241 |
+
with pd.ExcelWriter(buffer_records, engine='openpyxl') as writer:
|
| 242 |
+
records_df.drop(columns=['id']).to_excel(writer, index=False)
|
| 243 |
+
st.download_button("📥 세특 보관함 다운로드 (Excel)", data=buffer_records.getvalue(), file_name=f"{room_name}_세특보관함.xlsx")
|
| 244 |
+
with col_del:
|
| 245 |
+
st.selectbox("🗑️ 삭제할 '고유 번호(No.)' 선택", records_df['id'].tolist(), key="del_record_dropdown")
|
| 246 |
+
st.button("선택한 세특 기록 영구 삭제", type="primary", on_click=delete_selected_record)
|
| 247 |
+
else:
|
| 248 |
+
st.info("저장된 기록이 없습니다.")
|
| 249 |
+
|
| 250 |
+
teacher_record_section()
|
| 251 |
+
|
| 252 |
+
st.divider()
|
| 253 |
+
st.subheader("🚨 위험 구역 (방 폭파)")
|
| 254 |
+
with st.expander("이 방 전체 삭제하기 (클릭 시 펼쳐짐)", expanded=False):
|
| 255 |
+
if not ROOM_DESTROY_ENABLED:
|
| 256 |
+
st.warning("운영 안전 모드로 방 폭파 기능이 비활성화되어 있습니다.")
|
| 257 |
+
else:
|
| 258 |
+
st.error(f"🚨 경고: '{room_name}' 방의 모든 {act_type} 기록과 세특 보관함이 완전히 삭제됩니다.")
|
| 259 |
+
if st.button(f"네, '{room_name}' 방의 모든 데이터를 영구 삭제합니다", type="primary", use_container_width=True):
|
| 260 |
+
try:
|
| 261 |
+
if destroy_room_data(supabase, room_name) is None:
|
| 262 |
+
st.stop()
|
| 263 |
+
log_audit("room_destroyed", room_name=room_name, actor_name=student_name, role=user_role)
|
| 264 |
+
st.success("성공적으로 파괴되었습니다.")
|
| 265 |
+
st.session_state['ai_result_text'] = ""
|
| 266 |
+
st.rerun()
|
| 267 |
+
except Exception as e:
|
| 268 |
+
st.error(f"삭제 중 오류 발생: {e}")
|
config.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from db import _get_secret
|
| 2 |
+
|
| 3 |
+
AI_MODEL_NAME = "gemini-2.5-flash"
|
| 4 |
+
LIVE_BOARD_FETCH_LIMIT = 300
|
| 5 |
+
DASHBOARD_FETCH_LIMIT = 2000
|
| 6 |
+
RECORDS_FETCH_LIMIT = 500
|
| 7 |
+
LIVE_REFRESH_INTERVAL = "5s"
|
| 8 |
+
AI_HINT_ENABLED = str(_get_secret("AI_HINT_ENABLED", "true")).lower() not in ("false", "0", "no")
|
| 9 |
+
ROOM_DESTROY_ENABLED = str(_get_secret("ROOM_DESTROY_ENABLED", "true")).lower() not in ("false", "0", "no")
|
| 10 |
+
AUTO_JOIN_ON_REFRESH = str(_get_secret("AUTO_JOIN_ON_REFRESH", "false")).lower() not in ("false", "0", "no")
|
| 11 |
+
MAX_ROOM_NAME_LEN = 60
|
| 12 |
+
MAX_STUDENT_NAME_LEN = 30
|
| 13 |
+
MAX_TOPIC_LEN = 120
|
| 14 |
+
MAX_ENTRY_CODE_LEN = 60
|
| 15 |
+
UI_FONT_FAMILY = "sans-serif"
|
| 16 |
+
|
| 17 |
+
APP_CSS = """
|
| 18 |
+
<style>
|
| 19 |
+
.records-db-table-wrap { overflow-x: auto; border: 1px solid #e6e6e6; border-radius: 10px; background: #fff; }
|
| 20 |
+
.records-db-table-wrap table { width: 100%; border-collapse: collapse; table-layout: fixed; }
|
| 21 |
+
.records-db-table-wrap th, .records-db-table-wrap td { border-bottom: 1px solid #efefef; border-right: 1px solid #efefef; padding: 10px 12px; text-align: left; vertical-align: top; }
|
| 22 |
+
.records-db-table-wrap th:last-child, .records-db-table-wrap td:last-child { border-right: none; }
|
| 23 |
+
.records-db-table-wrap th { white-space: nowrap; font-weight: 700; }
|
| 24 |
+
.records-db-table-wrap th:nth-child(1), .records-db-table-wrap td:nth-child(1) { width: 5%; white-space: nowrap; }
|
| 25 |
+
.records-db-table-wrap th:nth-child(2), .records-db-table-wrap td:nth-child(2) { width: 15%; white-space: nowrap; }
|
| 26 |
+
.records-db-table-wrap th:nth-child(3), .records-db-table-wrap td:nth-child(3) { width: 12%; white-space: nowrap; }
|
| 27 |
+
.records-db-table-wrap th:nth-child(4), .records-db-table-wrap td:nth-child(4) { width: 68%; white-space: pre-wrap; word-break: break-word; }
|
| 28 |
+
[data-testid="stDecoration"] { display: none !important; }
|
| 29 |
+
.stApp, [data-testid="stAppViewContainer"], [data-testid="stMainBlockContainer"],
|
| 30 |
+
[data-testid="stAppViewBlockContainer"], [data-testid="stFragment"],
|
| 31 |
+
[data-testid="stVerticalBlock"], [data-testid="stElementContainer"],
|
| 32 |
+
[data-testid="stExpander"], details, summary,
|
| 33 |
+
*[data-stale="true"], div[data-stale="true"] {
|
| 34 |
+
opacity: 1 !important; transition: none !important; filter: none !important; -webkit-filter: none !important;
|
| 35 |
+
}
|
| 36 |
+
.stTextArea textarea, .stTextInput input, .stSelectbox, .stRadio label,
|
| 37 |
+
.stMarkdown p, div[data-testid="stChatMessageContent"] { font-size: 18px !important; }
|
| 38 |
+
.stAlert p { font-size: 20px !important; font-weight: bold; }
|
| 39 |
+
</style>
|
| 40 |
+
"""
|
pages/__init__.py
ADDED
|
File without changes
|
pages/admin.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from db import fetch_pending_teacher_accounts, approve_teacher_account
|
| 3 |
+
from utils import format_kst_datetime, get_kst_now_str
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def render_admin_approval_panel(supabase):
|
| 7 |
+
st.subheader("📝 교사 계정 승인")
|
| 8 |
+
pending_accounts = fetch_pending_teacher_accounts(supabase)
|
| 9 |
+
if not pending_accounts:
|
| 10 |
+
st.info("승인 대기 중인 교사 계정이 없습니다.")
|
| 11 |
+
return
|
| 12 |
+
for pending in pending_accounts:
|
| 13 |
+
acc_id = pending.get("id")
|
| 14 |
+
pending_teacher_id = pending.get("teacher_id", "")
|
| 15 |
+
requested_at = pending.get("requested_at", "") or "-"
|
| 16 |
+
c_left, c_right = st.columns([3, 2])
|
| 17 |
+
with c_left:
|
| 18 |
+
st.write(f"ID: {pending_teacher_id}")
|
| 19 |
+
with c_right:
|
| 20 |
+
st.caption(f"신청 시각: {format_kst_datetime(requested_at)}")
|
| 21 |
+
if st.button("승인", key=f"approve_{acc_id}"):
|
| 22 |
+
res = approve_teacher_account(supabase, acc_id, get_kst_now_str())
|
| 23 |
+
if res is not None:
|
| 24 |
+
st.success(f"{pending_teacher_id} 계정을 승인했습니다.")
|
| 25 |
+
st.rerun()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def render_admin_page(supabase, user_role, teacher_auth, admin_auth):
|
| 29 |
+
if not (user_role == "교사" and teacher_auth and admin_auth):
|
| 30 |
+
st.session_state['page'] = "lobby"
|
| 31 |
+
st.toast("관리자 페이지에서 나와 대기실로 이동했습니다.", icon="ℹ️")
|
| 32 |
+
st.rerun()
|
| 33 |
+
st.title("🛠️ 관리자 ID 요청 수락 페이지")
|
| 34 |
+
render_admin_approval_panel(supabase)
|
| 35 |
+
st.stop()
|
pages/home.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def render_home_page():
|
| 5 |
+
st.title("🏠 말자취(Talk-Trace) AI 홈")
|
| 6 |
+
st.markdown(
|
| 7 |
+
"""
|
| 8 |
+
### 사용 방법 (간단 안내)
|
| 9 |
+
1. **대기실로 이동** 버튼을 눌러 시작합니다.
|
| 10 |
+
2. 왼쪽 사이드바에서 **학생/교사 모드**를 선택합니다.
|
| 11 |
+
3. 접속할 **토론/토의방**을 선택하고 입장합니다.
|
| 12 |
+
4. 주제에 맞게 의견을 작성하고 제출하면 실시간 보드에 반영됩니다.
|
| 13 |
+
---
|
| 14 |
+
- 교사 모드에서는 방 개설/관리 및 대시보드 기능을 사용할 수 있습니다.
|
| 15 |
+
- 언제든 왼쪽 상단의 **🏠 홈** 버튼으로 이 화면으로 돌아올 수 있습니다.
|
| 16 |
+
"""
|
| 17 |
+
)
|
| 18 |
+
if st.button("🚀 대기실로 이동", type="primary", use_container_width=True):
|
| 19 |
+
st.session_state['page'] = "lobby"
|
| 20 |
+
st.rerun()
|
| 21 |
+
st.stop()
|
pages/lobby.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from db import fetch_room_entry_code
|
| 3 |
+
from validators import normalize_user_text
|
| 4 |
+
from config import AUTO_JOIN_ON_REFRESH
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def render_lobby_page(supabase, user_role, teacher_auth, room_name, student_number):
|
| 8 |
+
st.title("🚪 말자취(Talk-Trace) AI 대기실")
|
| 9 |
+
if user_role == "교사" and not teacher_auth:
|
| 10 |
+
st.warning("🚨 승인된 교사 계정으로 로그인해야 입장할 수 있습니다.")
|
| 11 |
+
elif not room_name.strip():
|
| 12 |
+
st.error("🚨 접속할 방을 먼저 선택해 주세요.")
|
| 13 |
+
else:
|
| 14 |
+
if user_role == "학생":
|
| 15 |
+
student_pw = st.text_input("🔒 방 입장 암호 (공개방이면 비워두세요)", type="password")
|
| 16 |
+
if st.button(f"🚀 '{room_name}' 입장하기", type="primary", use_container_width=True):
|
| 17 |
+
real_pw = fetch_room_entry_code(supabase, room_name)
|
| 18 |
+
if real_pw is None:
|
| 19 |
+
st.error("🚨 방 암호 정보를 확인할 수 없어 입장을 차단했습니다. 잠시 후 다시 시도해 주세요.")
|
| 20 |
+
elif real_pw and student_pw != real_pw:
|
| 21 |
+
st.error("❌ 암호가 틀렸습니다.")
|
| 22 |
+
elif not normalize_user_text(student_number, max_len=20):
|
| 23 |
+
st.error("❌ 학번을 입력해야 입장할 수 있습니다.")
|
| 24 |
+
else:
|
| 25 |
+
st.session_state['joined'] = True
|
| 26 |
+
st.rerun()
|
| 27 |
+
else:
|
| 28 |
+
if AUTO_JOIN_ON_REFRESH and teacher_auth:
|
| 29 |
+
st.session_state['joined'] = True
|
| 30 |
+
st.rerun()
|
| 31 |
+
if st.button(f"🚀 '{room_name}' 관리자 권한으로 입장", type="primary", use_container_width=True):
|
| 32 |
+
st.session_state['joined'] = True
|
| 33 |
+
st.rerun()
|
| 34 |
+
st.stop()
|