Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -86,6 +86,7 @@ ensure_db_login(supabase)
|
|
| 86 |
def get_kst_now():
|
| 87 |
return datetime.utcnow() + timedelta(hours=9)
|
| 88 |
|
|
|
|
| 89 |
def get_kst_now_str():
|
| 90 |
return get_kst_now().strftime(DATETIME_FMT)
|
| 91 |
|
|
@@ -162,7 +163,6 @@ def build_word_frequencies(text_series):
|
|
| 162 |
cleaned = re.sub(r"^[^\w가-힣]+|[^\w가-힣]+$", "", token)
|
| 163 |
if len(cleaned) < 2:
|
| 164 |
return ""
|
| 165 |
-
|
| 166 |
normalized = cleaned
|
| 167 |
for suffix in particle_suffixes:
|
| 168 |
if normalized.endswith(suffix) and len(normalized) > len(suffix) + 1:
|
|
@@ -291,7 +291,7 @@ def render_admin_approval_panel():
|
|
| 291 |
st.rerun()
|
| 292 |
|
| 293 |
# ==========================================
|
| 294 |
-
# [2] 앱 기본 설정 및 세션/CSS
|
| 295 |
# ==========================================
|
| 296 |
st.set_page_config(page_title="말자취(Talk-Trace) AI", layout="wide")
|
| 297 |
|
|
@@ -407,7 +407,6 @@ def compact_ai_report_output(text):
|
|
| 407 |
if not cleaned:
|
| 408 |
return ""
|
| 409 |
|
| 410 |
-
# 모델이 한 줄로 반환한 경우 라벨 기준으로 강제 줄바꿈
|
| 411 |
report_labels = ("핵심요약 1:", "핵심요약 2:", "핵심요약 3:", "베스트 학생:", "선정 이유:")
|
| 412 |
normalized_text = " ".join(cleaned)
|
| 413 |
if report_labels[0] in normalized_text:
|
|
@@ -416,8 +415,6 @@ def compact_ai_report_output(text):
|
|
| 416 |
normalized_text = normalized_text.replace(label, f"\n{label}")
|
| 417 |
|
| 418 |
normalized_lines = [line.strip() for line in normalized_text.splitlines() if line.strip()]
|
| 419 |
-
|
| 420 |
-
# 과도하게 긴 보고서 형태 출력 방지: 핵심 5줄만 유지
|
| 421 |
max_lines = 5
|
| 422 |
compact_lines = normalized_lines[:max_lines]
|
| 423 |
return "\n".join(compact_lines)
|
|
@@ -477,9 +474,13 @@ with st.sidebar:
|
|
| 477 |
auth_mode = st.radio("교사 계정", ["로그인", "ID/PW 신청"], horizontal=True)
|
| 478 |
|
| 479 |
if auth_mode == "로그인":
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
id_ok, safe_teacher_id, id_error_code, id_error_message = validate_teacher_credential(
|
| 484 |
teacher_id_input,
|
| 485 |
field_name="교사 ID",
|
|
@@ -575,7 +576,7 @@ with st.sidebar:
|
|
| 575 |
admin_auth = st.session_state['admin_auth']
|
| 576 |
teacher_id_for_scope = st.session_state.get("teacher_id", "")
|
| 577 |
|
| 578 |
-
#
|
| 579 |
if teacher_auth:
|
| 580 |
st.caption(f"🔐 {teacher_id_for_scope} 로그인 중")
|
| 581 |
if st.button("🚪 로그아웃", use_container_width=True):
|
|
@@ -586,7 +587,7 @@ with st.sidebar:
|
|
| 586 |
st.session_state['page'] = "lobby"
|
| 587 |
st.rerun()
|
| 588 |
st.divider()
|
| 589 |
-
|
| 590 |
if teacher_auth and admin_auth:
|
| 591 |
st.caption("관리자 바로가기")
|
| 592 |
if st.button("📝 ID 요청 수락", use_container_width=True):
|
|
@@ -702,7 +703,6 @@ if not st.session_state['joined']:
|
|
| 702 |
student_pw = st.text_input("🔒 방 입장 암호 (공개방이면 비워두세요)", type="password")
|
| 703 |
if st.button(f"🚀 '{room_name}' 입장하기", type="primary", use_container_width=True):
|
| 704 |
real_pw = fetch_room_entry_code(supabase, room_name)
|
| 705 |
-
|
| 706 |
if real_pw is None:
|
| 707 |
st.error("🚨 방 암호 정보를 확인할 수 없어 입장을 차단했습니다. 잠시 후 다시 시도해 주세요.")
|
| 708 |
elif real_pw and student_pw != real_pw:
|
|
@@ -808,10 +808,10 @@ st.divider()
|
|
| 808 |
# ==========================================
|
| 809 |
def live_chat_board_core():
|
| 810 |
board_df = fetch_live_messages(supabase, room_name, LIVE_BOARD_FETCH_LIMIT)
|
| 811 |
-
opinion_df = with_fallback_author_role(board_df)
|
| 812 |
stats_df = fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT)
|
| 813 |
stats_opinion_df = with_fallback_author_role(stats_df)
|
| 814 |
-
|
| 815 |
with st.expander("📊 실시간 의견 통계 보기 (클릭하여 펼치기)"):
|
| 816 |
if not stats_opinion_df.empty:
|
| 817 |
left_col, right_col = st.columns(2)
|
|
@@ -834,18 +834,18 @@ def live_chat_board_core():
|
|
| 834 |
|
| 835 |
col_board_title, col_board_ref = st.columns([8, 2])
|
| 836 |
with col_board_title:
|
| 837 |
-
st.subheader(f"💬 실시간 {act_type} 보드")
|
| 838 |
with col_board_ref:
|
| 839 |
if user_role == "교사" and teacher_auth:
|
| 840 |
st.button("🔄 실시간 보드 새로고침", use_container_width=True, key="refresh_chat_board")
|
| 841 |
-
|
| 842 |
if not opinion_df.empty:
|
| 843 |
teacher_df = opinion_df[opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 844 |
if not teacher_df.empty:
|
| 845 |
st.success(f"👨🏫 **선생님의 생각 힌트!** ➡️ {teacher_df.iloc[0]['content']}")
|
| 846 |
|
| 847 |
student_df = opinion_df[~opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 848 |
-
|
| 849 |
def delete_chat_msg(msg_id):
|
| 850 |
try:
|
| 851 |
if delete_opinion_message(supabase, msg_id) is None:
|
|
@@ -859,14 +859,14 @@ def live_chat_board_core():
|
|
| 859 |
formatted_timestamp = format_kst_datetime(row.get("timestamp", ""))
|
| 860 |
if user_role == "교사" and teacher_auth:
|
| 861 |
c_name, c_btn = st.columns([5, 1])
|
| 862 |
-
with c_name:
|
| 863 |
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 864 |
row_ip = str(row.get("ip_address", "")).strip() if hasattr(row, "get") else ""
|
| 865 |
if row_ip:
|
| 866 |
st.caption(f"IP: {mask_ip_for_teacher(row_ip)}")
|
| 867 |
with c_btn:
|
| 868 |
st.button("❌", key=f"del_{row['id']}", help="강제 삭제", on_click=delete_chat_msg, args=(row['id'],))
|
| 869 |
-
st.info(row['content'])
|
| 870 |
else:
|
| 871 |
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 872 |
st.info(row['content'])
|
|
@@ -896,7 +896,8 @@ def live_chat_board_core():
|
|
| 896 |
st.markdown("### ❓ 질문")
|
| 897 |
with st.container(height=450):
|
| 898 |
for _, row in student_df[student_df['sentiment'] == '❓ 질문'].iterrows(): render_msg(row)
|
| 899 |
-
else:
|
|
|
|
| 900 |
|
| 901 |
@st.fragment(run_every=LIVE_REFRESH_INTERVAL)
|
| 902 |
def live_chat_board_auto():
|
|
@@ -915,7 +916,7 @@ else:
|
|
| 915 |
# ==========================================
|
| 916 |
if user_role == "교사" and teacher_auth:
|
| 917 |
st.divider()
|
| 918 |
-
|
| 919 |
col_dash_title, col_dash_refresh = st.columns([8, 2])
|
| 920 |
with col_dash_title:
|
| 921 |
st.header("👨🏫 교사 관리 대시보드")
|
|
@@ -927,7 +928,7 @@ if user_role == "교사" and teacher_auth:
|
|
| 927 |
render_admin_approval_panel()
|
| 928 |
st.divider()
|
| 929 |
df_all = with_fallback_author_role(fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT))
|
| 930 |
-
|
| 931 |
# --- 1. 통계 ---
|
| 932 |
st.subheader("📊 학생 참여도 현황")
|
| 933 |
if not df_all.empty:
|
|
@@ -935,29 +936,29 @@ if user_role == "교사" and teacher_auth:
|
|
| 935 |
if not student_only_df.empty:
|
| 936 |
counts = student_only_df['student_name'].astype(str).value_counts().reset_index()
|
| 937 |
counts.columns = ['학생 이름', '참여 횟수']
|
| 938 |
-
counts['학생 이름'] = counts['학생 이름'] + " "
|
| 939 |
fig = px.bar(counts, x='학생 이름', y='참여 횟수', text='참여 횟수', color='학생 이름')
|
| 940 |
-
fig.update_xaxes(type='category', title="")
|
| 941 |
fig.update_layout(yaxis_title="의견 수", dragmode=False, showlegend=False, font={"family": UI_FONT_FAMILY})
|
| 942 |
st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': False, 'displayModeBar': False})
|
| 943 |
else: st.info("실명 참여 데이터가 없습니다.")
|
| 944 |
else: st.info(f"{act_type} 데이터가 없습니다.")
|
| 945 |
-
|
| 946 |
st.divider()
|
| 947 |
-
|
| 948 |
# --- 2. Teacher in the loop ---
|
| 949 |
@st.fragment
|
| 950 |
def teacher_hint_section():
|
| 951 |
st.subheader(f"💡 AI {act_type} 촉진 (Teacher-in-the-loop)")
|
| 952 |
st.info("AI 제안을 수정 후 전송하세요.")
|
| 953 |
-
|
| 954 |
def send_hint():
|
| 955 |
val = st.session_state.get('hint_input_widget', '').strip()
|
| 956 |
if val:
|
| 957 |
now = get_kst_now_str()
|
| 958 |
try:
|
| 959 |
res = create_teacher_hint(supabase, {
|
| 960 |
-
"room_name": room_name, "timestamp": now, "student_name": "👨🏫 선생님 (AI 보조)",
|
| 961 |
"content": val, "sentiment": "❓ 질문", "author_role": "교사"
|
| 962 |
})
|
| 963 |
if res is None:
|
|
@@ -966,7 +967,7 @@ if user_role == "교사" and teacher_auth:
|
|
| 966 |
st.session_state['hint_input_widget'] = ""
|
| 967 |
except Exception as e:
|
| 968 |
st.error(f"힌트 전송 실패: {e}")
|
| 969 |
-
|
| 970 |
if AI_HINT_ENABLED:
|
| 971 |
if st.button("🪄 AI 힌트 초안 생성", use_container_width=True):
|
| 972 |
st.toast("👀 AI가 대화 맥락을 읽고 있습니다...", icon="⏳")
|
|
@@ -995,7 +996,7 @@ if user_role == "교사" and teacher_auth:
|
|
| 995 |
st.text_input("선생님의 검토 및 수정", key="hint_input_widget", label_visibility="collapsed", placeholder="여기에 AI 힌트가 나타납니다.")
|
| 996 |
with col_edit_btn:
|
| 997 |
st.button("🚀 학생 화면 전송", use_container_width=True, type="primary", on_click=send_hint)
|
| 998 |
-
|
| 999 |
teacher_hint_section()
|
| 1000 |
st.divider()
|
| 1001 |
|
|
@@ -1003,7 +1004,7 @@ if user_role == "교사" and teacher_auth:
|
|
| 1003 |
@st.fragment
|
| 1004 |
def teacher_summary_section():
|
| 1005 |
st.subheader(f"📝 수업 종료 및 전체 {act_type} 요약 리포트")
|
| 1006 |
-
|
| 1007 |
if st.button(f"{act_type} 요약 및 베스트 발언 추출 🪄", use_container_width=True):
|
| 1008 |
st.toast("👀 AI가 전체 기록을 꼼꼼히 읽고 있습니다...", icon="⏳")
|
| 1009 |
with st.spinner("✍️ 요약 리포트를 작성하고 있습니다..."):
|
|
@@ -1046,7 +1047,7 @@ if user_role == "교사" and teacher_auth:
|
|
| 1046 |
f"<div style='line-height:1.8;'>{report_html}</div>",
|
| 1047 |
unsafe_allow_html=True,
|
| 1048 |
)
|
| 1049 |
-
|
| 1050 |
teacher_summary_section()
|
| 1051 |
st.divider()
|
| 1052 |
|
|
@@ -1075,10 +1076,10 @@ if user_role == "교사" and teacher_auth:
|
|
| 1075 |
with col4:
|
| 1076 |
st.subheader("🤖 개인별 AI 세특 초안 생성")
|
| 1077 |
student_list = student_only_df['student_name'].unique() if not df_all.empty else []
|
| 1078 |
-
|
| 1079 |
if len(student_list) > 0:
|
| 1080 |
selected_student = st.selectbox("학생을 선택하세요", student_list)
|
| 1081 |
-
|
| 1082 |
if st.button(f"'{selected_student}' 세특 생성 🪄", use_container_width=True):
|
| 1083 |
st.toast(f"👀 AI가 '{selected_student}' 학생의 활동을 분석합니다...", icon="⏳")
|
| 1084 |
with st.spinner(f"✍️ '{selected_student}' 학생의 세특 초안 작성 중..."):
|
|
@@ -1094,12 +1095,12 @@ if user_role == "교사" and teacher_auth:
|
|
| 1094 |
room_name=room_name,
|
| 1095 |
student=selected_student,
|
| 1096 |
)
|
| 1097 |
-
|
| 1098 |
if res_text:
|
| 1099 |
st.session_state['ai_result_text'] = res_text
|
| 1100 |
now = get_kst_now_str()
|
| 1101 |
save_res = save_student_record(supabase, {
|
| 1102 |
-
"room_name": room_name, "timestamp": now,
|
| 1103 |
"student_name": selected_student, "content": res_text
|
| 1104 |
})
|
| 1105 |
if save_res is None:
|
|
@@ -1110,7 +1111,7 @@ if user_role == "교사" and teacher_auth:
|
|
| 1110 |
except Exception as e:
|
| 1111 |
logger.exception("세특 생성 후처리 실패")
|
| 1112 |
st.toast("🚨 오류가 발생했습니다. 다시 시도해주세요.", icon="❌")
|
| 1113 |
-
|
| 1114 |
if st.session_state.get('ai_result_text'):
|
| 1115 |
st.success("🤖 **개인별 세특 초안** (보관함에 자동 저장되었습니다)")
|
| 1116 |
st.text_area("내용 수정 후 복사하여 사용하세요", value=st.session_state['ai_result_text'], height=200, label_visibility="collapsed")
|
|
@@ -1118,7 +1119,7 @@ if user_role == "교사" and teacher_auth:
|
|
| 1118 |
|
| 1119 |
st.divider()
|
| 1120 |
st.subheader("📂 저장된 세특 기록 보관함")
|
| 1121 |
-
|
| 1122 |
records_df = fetch_student_records(supabase, room_name, RECORDS_FETCH_LIMIT)
|
| 1123 |
|
| 1124 |
if not records_df.empty:
|
|
@@ -1128,15 +1129,15 @@ if user_role == "교사" and teacher_auth:
|
|
| 1128 |
col_down, col_del = st.columns([1, 1])
|
| 1129 |
with col_down:
|
| 1130 |
buffer_records = io.BytesIO()
|
| 1131 |
-
with pd.ExcelWriter(buffer_records, engine='openpyxl') as writer:
|
| 1132 |
records_df.drop(columns=['id']).to_excel(writer, index=False)
|
| 1133 |
st.download_button("📥 세특 보관함 다운로드 (Excel)", data=buffer_records.getvalue(), file_name=f"{room_name}_세특보관함.xlsx")
|
| 1134 |
-
|
| 1135 |
with col_del:
|
| 1136 |
st.selectbox("🗑️ 삭제할 '고유 번호(No.)' 선택", records_df['id'].tolist(), key="del_record_dropdown")
|
| 1137 |
st.button("선택한 세특 ��록 영구 삭제", type="primary", on_click=delete_selected_record)
|
| 1138 |
else: st.info("저장된 기록이 없습니다.")
|
| 1139 |
-
|
| 1140 |
teacher_record_section()
|
| 1141 |
|
| 1142 |
st.divider()
|
|
@@ -1153,6 +1154,6 @@ if user_role == "교사" and teacher_auth:
|
|
| 1153 |
log_audit("room_destroyed", room_name=room_name, actor_name=student_name, role=user_role)
|
| 1154 |
st.success("성공적으로 파괴되었습니다.")
|
| 1155 |
st.session_state['ai_result_text'] = ""
|
| 1156 |
-
st.rerun()
|
| 1157 |
except Exception as e:
|
| 1158 |
st.error(f"삭제 중 오류 발생: {e}")
|
|
|
|
| 86 |
def get_kst_now():
|
| 87 |
return datetime.utcnow() + timedelta(hours=9)
|
| 88 |
|
| 89 |
+
# ✅ 수정 1: 중복 정의 제거 — get_kst_now_str() 하나만 유지
|
| 90 |
def get_kst_now_str():
|
| 91 |
return get_kst_now().strftime(DATETIME_FMT)
|
| 92 |
|
|
|
|
| 163 |
cleaned = re.sub(r"^[^\w가-힣]+|[^\w가-힣]+$", "", token)
|
| 164 |
if len(cleaned) < 2:
|
| 165 |
return ""
|
|
|
|
| 166 |
normalized = cleaned
|
| 167 |
for suffix in particle_suffixes:
|
| 168 |
if normalized.endswith(suffix) and len(normalized) > len(suffix) + 1:
|
|
|
|
| 291 |
st.rerun()
|
| 292 |
|
| 293 |
# ==========================================
|
| 294 |
+
# [2] 앱 기본 설정 및 세션/CSS
|
| 295 |
# ==========================================
|
| 296 |
st.set_page_config(page_title="말자취(Talk-Trace) AI", layout="wide")
|
| 297 |
|
|
|
|
| 407 |
if not cleaned:
|
| 408 |
return ""
|
| 409 |
|
|
|
|
| 410 |
report_labels = ("핵심요약 1:", "핵심요약 2:", "핵심요약 3:", "베스트 학생:", "선정 이유:")
|
| 411 |
normalized_text = " ".join(cleaned)
|
| 412 |
if report_labels[0] in normalized_text:
|
|
|
|
| 415 |
normalized_text = normalized_text.replace(label, f"\n{label}")
|
| 416 |
|
| 417 |
normalized_lines = [line.strip() for line in normalized_text.splitlines() if line.strip()]
|
|
|
|
|
|
|
| 418 |
max_lines = 5
|
| 419 |
compact_lines = normalized_lines[:max_lines]
|
| 420 |
return "\n".join(compact_lines)
|
|
|
|
| 474 |
auth_mode = st.radio("교사 계정", ["로그인", "ID/PW 신청"], horizontal=True)
|
| 475 |
|
| 476 |
if auth_mode == "로그인":
|
| 477 |
+
# ✅ 수정 2: st.form으로 감싸서 엔터키로 로그인 가능하도록 수정
|
| 478 |
+
with st.form("teacher_login_form"):
|
| 479 |
+
teacher_id_input = st.text_input("교사 ID", key="teacher_id_input")
|
| 480 |
+
teacher_pw_input = st.text_input("교사 PW", type="password", key="teacher_pw_input")
|
| 481 |
+
login_submitted = st.form_submit_button("교사 로그인", use_container_width=True)
|
| 482 |
+
|
| 483 |
+
if login_submitted:
|
| 484 |
id_ok, safe_teacher_id, id_error_code, id_error_message = validate_teacher_credential(
|
| 485 |
teacher_id_input,
|
| 486 |
field_name="교사 ID",
|
|
|
|
| 576 |
admin_auth = st.session_state['admin_auth']
|
| 577 |
teacher_id_for_scope = st.session_state.get("teacher_id", "")
|
| 578 |
|
| 579 |
+
# ✅ 수정 3: 로그아웃 버튼 추가
|
| 580 |
if teacher_auth:
|
| 581 |
st.caption(f"🔐 {teacher_id_for_scope} 로그인 중")
|
| 582 |
if st.button("🚪 로그아웃", use_container_width=True):
|
|
|
|
| 587 |
st.session_state['page'] = "lobby"
|
| 588 |
st.rerun()
|
| 589 |
st.divider()
|
| 590 |
+
|
| 591 |
if teacher_auth and admin_auth:
|
| 592 |
st.caption("관리자 바로가기")
|
| 593 |
if st.button("📝 ID 요청 수락", use_container_width=True):
|
|
|
|
| 703 |
student_pw = st.text_input("🔒 방 입장 암호 (공개방이면 비워두세요)", type="password")
|
| 704 |
if st.button(f"🚀 '{room_name}' 입장하기", type="primary", use_container_width=True):
|
| 705 |
real_pw = fetch_room_entry_code(supabase, room_name)
|
|
|
|
| 706 |
if real_pw is None:
|
| 707 |
st.error("🚨 방 암호 정보를 확인할 수 없어 입장을 차단했습니다. 잠시 후 다시 시도해 주세요.")
|
| 708 |
elif real_pw and student_pw != real_pw:
|
|
|
|
| 808 |
# ==========================================
|
| 809 |
def live_chat_board_core():
|
| 810 |
board_df = fetch_live_messages(supabase, room_name, LIVE_BOARD_FETCH_LIMIT)
|
| 811 |
+
opinion_df = with_fallback_author_role(board_df)
|
| 812 |
stats_df = fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT)
|
| 813 |
stats_opinion_df = with_fallback_author_role(stats_df)
|
| 814 |
+
|
| 815 |
with st.expander("📊 실시간 의견 통계 보기 (클릭하여 펼치기)"):
|
| 816 |
if not stats_opinion_df.empty:
|
| 817 |
left_col, right_col = st.columns(2)
|
|
|
|
| 834 |
|
| 835 |
col_board_title, col_board_ref = st.columns([8, 2])
|
| 836 |
with col_board_title:
|
| 837 |
+
st.subheader(f"💬 실시간 {act_type} 보드")
|
| 838 |
with col_board_ref:
|
| 839 |
if user_role == "교사" and teacher_auth:
|
| 840 |
st.button("🔄 실시간 보드 새로고침", use_container_width=True, key="refresh_chat_board")
|
| 841 |
+
|
| 842 |
if not opinion_df.empty:
|
| 843 |
teacher_df = opinion_df[opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 844 |
if not teacher_df.empty:
|
| 845 |
st.success(f"👨🏫 **선생님의 생각 힌트!** ➡️ {teacher_df.iloc[0]['content']}")
|
| 846 |
|
| 847 |
student_df = opinion_df[~opinion_df['student_name'].str.contains('선생님', na=False)]
|
| 848 |
+
|
| 849 |
def delete_chat_msg(msg_id):
|
| 850 |
try:
|
| 851 |
if delete_opinion_message(supabase, msg_id) is None:
|
|
|
|
| 859 |
formatted_timestamp = format_kst_datetime(row.get("timestamp", ""))
|
| 860 |
if user_role == "교사" and teacher_auth:
|
| 861 |
c_name, c_btn = st.columns([5, 1])
|
| 862 |
+
with c_name:
|
| 863 |
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 864 |
row_ip = str(row.get("ip_address", "")).strip() if hasattr(row, "get") else ""
|
| 865 |
if row_ip:
|
| 866 |
st.caption(f"IP: {mask_ip_for_teacher(row_ip)}")
|
| 867 |
with c_btn:
|
| 868 |
st.button("❌", key=f"del_{row['id']}", help="강제 삭제", on_click=delete_chat_msg, args=(row['id'],))
|
| 869 |
+
st.info(row['content'])
|
| 870 |
else:
|
| 871 |
st.markdown(f"**{row['student_name']}** <span style='color:gray; font-size:14px;'>{formatted_timestamp}</span>", unsafe_allow_html=True)
|
| 872 |
st.info(row['content'])
|
|
|
|
| 896 |
st.markdown("### ❓ 질문")
|
| 897 |
with st.container(height=450):
|
| 898 |
for _, row in student_df[student_df['sentiment'] == '❓ 질문'].iterrows(): render_msg(row)
|
| 899 |
+
else:
|
| 900 |
+
st.info(f"아직 대화가 없습니다. 첫 {act_type} 의견을 남겨주세요!")
|
| 901 |
|
| 902 |
@st.fragment(run_every=LIVE_REFRESH_INTERVAL)
|
| 903 |
def live_chat_board_auto():
|
|
|
|
| 916 |
# ==========================================
|
| 917 |
if user_role == "교사" and teacher_auth:
|
| 918 |
st.divider()
|
| 919 |
+
|
| 920 |
col_dash_title, col_dash_refresh = st.columns([8, 2])
|
| 921 |
with col_dash_title:
|
| 922 |
st.header("👨🏫 교사 관리 대시보드")
|
|
|
|
| 928 |
render_admin_approval_panel()
|
| 929 |
st.divider()
|
| 930 |
df_all = with_fallback_author_role(fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT))
|
| 931 |
+
|
| 932 |
# --- 1. 통계 ---
|
| 933 |
st.subheader("📊 학생 참여도 현황")
|
| 934 |
if not df_all.empty:
|
|
|
|
| 936 |
if not student_only_df.empty:
|
| 937 |
counts = student_only_df['student_name'].astype(str).value_counts().reset_index()
|
| 938 |
counts.columns = ['학생 이름', '참여 횟수']
|
| 939 |
+
counts['학생 이름'] = counts['학생 이름'] + " "
|
| 940 |
fig = px.bar(counts, x='학생 이름', y='참여 횟수', text='참여 횟수', color='학생 이름')
|
| 941 |
+
fig.update_xaxes(type='category', title="")
|
| 942 |
fig.update_layout(yaxis_title="의견 수", dragmode=False, showlegend=False, font={"family": UI_FONT_FAMILY})
|
| 943 |
st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': False, 'displayModeBar': False})
|
| 944 |
else: st.info("실명 참여 데이터가 없습니다.")
|
| 945 |
else: st.info(f"{act_type} 데이터가 없습니다.")
|
| 946 |
+
|
| 947 |
st.divider()
|
| 948 |
+
|
| 949 |
# --- 2. Teacher in the loop ---
|
| 950 |
@st.fragment
|
| 951 |
def teacher_hint_section():
|
| 952 |
st.subheader(f"💡 AI {act_type} 촉진 (Teacher-in-the-loop)")
|
| 953 |
st.info("AI 제안을 수정 후 전송하세요.")
|
| 954 |
+
|
| 955 |
def send_hint():
|
| 956 |
val = st.session_state.get('hint_input_widget', '').strip()
|
| 957 |
if val:
|
| 958 |
now = get_kst_now_str()
|
| 959 |
try:
|
| 960 |
res = create_teacher_hint(supabase, {
|
| 961 |
+
"room_name": room_name, "timestamp": now, "student_name": "👨🏫 선생님 (AI 보조)",
|
| 962 |
"content": val, "sentiment": "❓ 질문", "author_role": "교사"
|
| 963 |
})
|
| 964 |
if res is None:
|
|
|
|
| 967 |
st.session_state['hint_input_widget'] = ""
|
| 968 |
except Exception as e:
|
| 969 |
st.error(f"힌트 전송 실패: {e}")
|
| 970 |
+
|
| 971 |
if AI_HINT_ENABLED:
|
| 972 |
if st.button("🪄 AI 힌트 초안 생성", use_container_width=True):
|
| 973 |
st.toast("👀 AI가 대화 맥락을 읽고 있습니다...", icon="⏳")
|
|
|
|
| 996 |
st.text_input("선생님의 검토 및 수정", key="hint_input_widget", label_visibility="collapsed", placeholder="여기에 AI 힌트가 나타납니다.")
|
| 997 |
with col_edit_btn:
|
| 998 |
st.button("🚀 학생 화면 전송", use_container_width=True, type="primary", on_click=send_hint)
|
| 999 |
+
|
| 1000 |
teacher_hint_section()
|
| 1001 |
st.divider()
|
| 1002 |
|
|
|
|
| 1004 |
@st.fragment
|
| 1005 |
def teacher_summary_section():
|
| 1006 |
st.subheader(f"📝 수업 종료 및 전체 {act_type} 요약 리포트")
|
| 1007 |
+
|
| 1008 |
if st.button(f"{act_type} 요약 및 베스트 발언 추출 🪄", use_container_width=True):
|
| 1009 |
st.toast("👀 AI가 전체 기록을 꼼꼼히 읽고 있습니다...", icon="⏳")
|
| 1010 |
with st.spinner("✍️ 요약 리포트를 작성하고 있습니다..."):
|
|
|
|
| 1047 |
f"<div style='line-height:1.8;'>{report_html}</div>",
|
| 1048 |
unsafe_allow_html=True,
|
| 1049 |
)
|
| 1050 |
+
|
| 1051 |
teacher_summary_section()
|
| 1052 |
st.divider()
|
| 1053 |
|
|
|
|
| 1076 |
with col4:
|
| 1077 |
st.subheader("🤖 개인별 AI 세특 초안 생성")
|
| 1078 |
student_list = student_only_df['student_name'].unique() if not df_all.empty else []
|
| 1079 |
+
|
| 1080 |
if len(student_list) > 0:
|
| 1081 |
selected_student = st.selectbox("학생을 선택하세요", student_list)
|
| 1082 |
+
|
| 1083 |
if st.button(f"'{selected_student}' 세특 생성 🪄", use_container_width=True):
|
| 1084 |
st.toast(f"👀 AI가 '{selected_student}' 학생의 활동을 분석합니다...", icon="⏳")
|
| 1085 |
with st.spinner(f"✍️ '{selected_student}' 학생의 세특 초안 작성 중..."):
|
|
|
|
| 1095 |
room_name=room_name,
|
| 1096 |
student=selected_student,
|
| 1097 |
)
|
| 1098 |
+
|
| 1099 |
if res_text:
|
| 1100 |
st.session_state['ai_result_text'] = res_text
|
| 1101 |
now = get_kst_now_str()
|
| 1102 |
save_res = save_student_record(supabase, {
|
| 1103 |
+
"room_name": room_name, "timestamp": now,
|
| 1104 |
"student_name": selected_student, "content": res_text
|
| 1105 |
})
|
| 1106 |
if save_res is None:
|
|
|
|
| 1111 |
except Exception as e:
|
| 1112 |
logger.exception("세특 생성 후처리 실패")
|
| 1113 |
st.toast("🚨 오류가 발생했습니다. 다시 시도해주세요.", icon="❌")
|
| 1114 |
+
|
| 1115 |
if st.session_state.get('ai_result_text'):
|
| 1116 |
st.success("🤖 **개인별 세특 초안** (보관함에 자동 저장되었습니다)")
|
| 1117 |
st.text_area("내용 수정 후 복사하여 사용하세요", value=st.session_state['ai_result_text'], height=200, label_visibility="collapsed")
|
|
|
|
| 1119 |
|
| 1120 |
st.divider()
|
| 1121 |
st.subheader("📂 저장된 세특 기록 보관함")
|
| 1122 |
+
|
| 1123 |
records_df = fetch_student_records(supabase, room_name, RECORDS_FETCH_LIMIT)
|
| 1124 |
|
| 1125 |
if not records_df.empty:
|
|
|
|
| 1129 |
col_down, col_del = st.columns([1, 1])
|
| 1130 |
with col_down:
|
| 1131 |
buffer_records = io.BytesIO()
|
| 1132 |
+
with pd.ExcelWriter(buffer_records, engine='openpyxl') as writer:
|
| 1133 |
records_df.drop(columns=['id']).to_excel(writer, index=False)
|
| 1134 |
st.download_button("📥 세특 보관함 다운로드 (Excel)", data=buffer_records.getvalue(), file_name=f"{room_name}_세특보관함.xlsx")
|
| 1135 |
+
|
| 1136 |
with col_del:
|
| 1137 |
st.selectbox("🗑️ 삭제할 '고유 번호(No.)' 선택", records_df['id'].tolist(), key="del_record_dropdown")
|
| 1138 |
st.button("선택한 세특 ��록 영구 삭제", type="primary", on_click=delete_selected_record)
|
| 1139 |
else: st.info("저장된 기록이 없습니다.")
|
| 1140 |
+
|
| 1141 |
teacher_record_section()
|
| 1142 |
|
| 1143 |
st.divider()
|
|
|
|
| 1154 |
log_audit("room_destroyed", room_name=room_name, actor_name=student_name, role=user_role)
|
| 1155 |
st.success("성공적으로 파괴되었습니다.")
|
| 1156 |
st.session_state['ai_result_text'] = ""
|
| 1157 |
+
st.rerun()
|
| 1158 |
except Exception as e:
|
| 1159 |
st.error(f"삭제 중 오류 발생: {e}")
|