VioletWizard commited on
Commit
d7bac00
·
unverified ·
1 Parent(s): a2795da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -29
app.py CHANGED
@@ -2,12 +2,10 @@ import streamlit as st
2
  import pandas as pd
3
  import io
4
  import html
5
- import os
6
  from collections import Counter
7
  from datetime import datetime, timedelta, timezone
8
  import logging
9
  import plotly.express as px
10
- from wordcloud import WordCloud
11
 
12
  from db import (
13
  approve_teacher_account,
@@ -148,19 +146,6 @@ def get_client_ip():
148
  def log_audit(event, room_name="", actor_name="", role="", **extra):
149
  logger.info("AUDIT event=%s room=%s actor=%s role=%s extra=%s", event, room_name, actor_name, role, extra)
150
 
151
- def resolve_wordcloud_font_path():
152
- candidate_paths = [
153
- "/usr/share/fonts/truetype/nanum/NanumGothic.ttf",
154
- "/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf",
155
- "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
156
- "/System/Library/Fonts/AppleSDGothicNeo.ttc",
157
- "C:/Windows/Fonts/malgun.ttf",
158
- ]
159
- for font_path in candidate_paths:
160
- if os.path.exists(font_path):
161
- return font_path
162
- return None
163
-
164
  def build_word_frequencies(text_series):
165
  tokens = []
166
  stopwords = {
@@ -178,6 +163,35 @@ def build_word_frequencies(text_series):
178
  tokens.append(cleaned)
179
  return Counter(tokens)
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  def render_admin_approval_panel():
182
  st.subheader("📝 교사 계정 승인")
183
  pending_accounts = fetch_pending_teacher_accounts(supabase)
@@ -709,30 +723,24 @@ st.divider()
709
  # [7] 실시간 업데이트 영역
710
  # ==========================================
711
  def live_chat_board_core():
712
- df = fetch_live_messages(supabase, room_name, LIVE_BOARD_FETCH_LIMIT)
713
- opinion_df = with_fallback_author_role(df) # 변수명 매칭 확인 (이전 코드에서 student_df 대신 opinion_df 혼용 부분 수정)
 
 
714
 
715
  with st.expander("📊 실시간 의견 통계 보기 (클릭하여 펼치기)"):
716
- if not opinion_df.empty:
717
  left_col, right_col = st.columns(2)
718
  with left_col:
719
  st.caption("감정 분포 그래프")
720
- live_pie_fig = px.pie(opinion_df, names="sentiment", hole=0.4, height=320)
721
  live_pie_fig.update_layout(font={"family": UI_FONT_FAMILY})
722
  st.plotly_chart(live_pie_fig, use_container_width=True, config={'displayModeBar': False, 'scrollZoom': False})
723
  with right_col:
724
  st.caption("누적 토의/토론 워드클라우드")
725
- frequencies = build_word_frequencies(opinion_df["content"])
726
  if frequencies:
727
- font_path = resolve_wordcloud_font_path()
728
- wc = WordCloud(
729
- width=900,
730
- height=500,
731
- background_color="white",
732
- colormap="viridis",
733
- font_path=font_path,
734
- ).generate_from_frequencies(frequencies)
735
- st.image(wc.to_array(), use_container_width=True)
736
  top_words = ", ".join([f"{word}({count})" for word, count in frequencies.most_common(8)])
737
  st.caption(f"상위 키워드: {top_words}")
738
  else:
 
2
  import pandas as pd
3
  import io
4
  import html
 
5
  from collections import Counter
6
  from datetime import datetime, timedelta, timezone
7
  import logging
8
  import plotly.express as px
 
9
 
10
  from db import (
11
  approve_teacher_account,
 
146
  def log_audit(event, room_name="", actor_name="", role="", **extra):
147
  logger.info("AUDIT event=%s room=%s actor=%s role=%s extra=%s", event, room_name, actor_name, role, extra)
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  def build_word_frequencies(text_series):
150
  tokens = []
151
  stopwords = {
 
163
  tokens.append(cleaned)
164
  return Counter(tokens)
165
 
166
+ def build_wordcloud_html(frequencies, max_words=60):
167
+ if not frequencies:
168
+ return ""
169
+
170
+ sorted_words = sorted(frequencies.items(), key=lambda item: (-item[1], item[0]))[:max_words]
171
+ max_count = sorted_words[0][1]
172
+ min_count = sorted_words[-1][1]
173
+ span_html = []
174
+ palette = ["#50327A", "#2A9D8F", "#3A86AF", "#88C057", "#D4C93D"]
175
+
176
+ for index, (word, count) in enumerate(sorted_words):
177
+ if max_count == min_count:
178
+ font_size = 26
179
+ else:
180
+ ratio = (count - min_count) / (max_count - min_count)
181
+ font_size = int(18 + ratio * 30)
182
+ color = palette[index % len(palette)]
183
+ span_html.append(
184
+ f"<span style='display:inline-block; margin:8px 10px; font-size:{font_size}px; "
185
+ f"font-weight:700; color:{color}; line-height:1.2;'>{html.escape(word)}</span>"
186
+ )
187
+
188
+ return (
189
+ "<div style='padding:14px; min-height:280px; border:1px solid #e9e9e9; border-radius:10px; "
190
+ "background:#ffffff; display:flex; flex-wrap:wrap; align-items:center; justify-content:center;'>"
191
+ + "".join(span_html) +
192
+ "</div>"
193
+ )
194
+
195
  def render_admin_approval_panel():
196
  st.subheader("📝 교사 계정 승인")
197
  pending_accounts = fetch_pending_teacher_accounts(supabase)
 
723
  # [7] 실시간 업데이트 영역
724
  # ==========================================
725
  def live_chat_board_core():
726
+ board_df = fetch_live_messages(supabase, room_name, LIVE_BOARD_FETCH_LIMIT)
727
+ opinion_df = with_fallback_author_role(board_df) # 변수명 매칭 확인 (이전 코드에서 student_df 대신 opinion_df 혼용 부분 수정)
728
+ stats_df = fetch_live_messages(supabase, room_name, DASHBOARD_FETCH_LIMIT)
729
+ stats_opinion_df = with_fallback_author_role(stats_df)
730
 
731
  with st.expander("📊 실시간 의견 통계 보기 (클릭하여 펼치기)"):
732
+ if not stats_opinion_df.empty:
733
  left_col, right_col = st.columns(2)
734
  with left_col:
735
  st.caption("감정 분포 그래프")
736
+ live_pie_fig = px.pie(stats_opinion_df, names="sentiment", hole=0.4, height=320)
737
  live_pie_fig.update_layout(font={"family": UI_FONT_FAMILY})
738
  st.plotly_chart(live_pie_fig, use_container_width=True, config={'displayModeBar': False, 'scrollZoom': False})
739
  with right_col:
740
  st.caption("누적 토의/토론 워드클라우드")
741
+ frequencies = build_word_frequencies(stats_opinion_df["content"])
742
  if frequencies:
743
+ st.markdown(build_wordcloud_html(frequencies), unsafe_allow_html=True)
 
 
 
 
 
 
 
 
744
  top_words = ", ".join([f"{word}({count})" for word, count in frequencies.most_common(8)])
745
  st.caption(f"상위 키워드: {top_words}")
746
  else: