Spaces:
Runtime error
Runtime error
Claude commited on
feat: AI 피드백 카드 (Work Item 5)
Browse files- opinion_changes.ai_feedback 컬럼 스키마 체크 추가
- save_opinion_feedback() DB 함수 추가
- build_feedback_prompt() AI 프롬프트 추가 (잘한 점 / 발전할 점)
- 생각 변화 제출 시 배움 분석 + 피드백 카드 동시 생성
- 학생 화면: 토론 후 피드백 카드 2단 컬럼 표시 (✅ 잘한 점 / 🌱 발전할 점)
- 교사 대시보드: 학생별 배움 분석에 피드백 카드 함께 표시
https://claude.ai/code/session_016DE3uHLsVmA5Uv7gZGGaKT
- components/opinion_change.py +54 -3
- components/teacher_dashboard.py +31 -4
- db.py +16 -0
- services/ai.py +17 -0
components/opinion_change.py
CHANGED
|
@@ -3,16 +3,18 @@ import streamlit as st
|
|
| 3 |
from config import AI_MODEL_NAME, LIVE_BOARD_FETCH_LIMIT
|
| 4 |
from utils import create_analysis_image, get_client_ip
|
| 5 |
from db import (
|
|
|
|
| 6 |
fetch_live_messages,
|
| 7 |
fetch_opinion_change,
|
| 8 |
opinion_changes_available,
|
| 9 |
save_opinion_analysis,
|
|
|
|
| 10 |
stance_available,
|
| 11 |
upsert_post_opinion,
|
| 12 |
upsert_pre_opinion,
|
| 13 |
)
|
| 14 |
from env import get_secret
|
| 15 |
-
from services.ai import build_opinion_change_prompt, generate_ai_response
|
| 16 |
|
| 17 |
|
| 18 |
_STANCE_OPTIONS = ["🔵 찬성", "🔴 반대"]
|
|
@@ -121,12 +123,43 @@ def render_post_opinion_section(supabase, room_name, student_name, act_type, cur
|
|
| 121 |
else:
|
| 122 |
final_stance_val = (row or {}).get("final_stance") or ""
|
| 123 |
discussion_conclusion_val = (row or {}).get("discussion_conclusion") or ""
|
|
|
|
| 124 |
if act_type == "토론" and final_stance_val:
|
| 125 |
st.success(f"✅ **최종 입장:** {final_stance_val}")
|
| 126 |
if act_type == "토의" and discussion_conclusion_val:
|
| 127 |
st.success(f"✅ **나의 결론:** {discussion_conclusion_val}")
|
| 128 |
st.success(f"✅ **토론 후 내 생각:** {post_opinion}")
|
| 129 |
st.divider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
if ai_analysis:
|
| 131 |
st.info("🤖 **AI 배움 분석**")
|
| 132 |
st.markdown(ai_analysis.replace("\n", "\n\n"))
|
|
@@ -178,23 +211,41 @@ def _trigger_analysis(supabase, room_name, student_name, act_type, current_topic
|
|
| 178 |
else:
|
| 179 |
debate_history = "(토론 발언 기록 없음)"
|
| 180 |
|
|
|
|
|
|
|
| 181 |
with st.spinner("🤖 AI가 배움의 변화를 분석하고 있습니다..."):
|
|
|
|
| 182 |
prompt = build_opinion_change_prompt(
|
| 183 |
act_type, current_topic, student_name, pre_opinion, post_opinion, debate_history
|
| 184 |
)
|
| 185 |
res_text = generate_ai_response(
|
| 186 |
prompt,
|
| 187 |
model_name=AI_MODEL_NAME,
|
| 188 |
-
api_key=
|
| 189 |
log_message="AI 생각 변화 분석 실패",
|
| 190 |
room_name=room_name,
|
| 191 |
student=student_name,
|
| 192 |
)
|
| 193 |
if res_text:
|
| 194 |
save_opinion_analysis(supabase, room_name, student_name, res_text)
|
| 195 |
-
# 캐시 초기화 — 새 분석 결과로 이미지 재생성
|
| 196 |
cache_key = f"img_{room_name}_{student_name}_bytes"
|
| 197 |
st.session_state.pop(cache_key, None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
st.toast("✅ AI 분석 완료!", icon="🎉")
|
| 199 |
else:
|
| 200 |
st.toast("🚨 AI 분석에 실패했습니다.", icon="❌")
|
|
|
|
| 3 |
from config import AI_MODEL_NAME, LIVE_BOARD_FETCH_LIMIT
|
| 4 |
from utils import create_analysis_image, get_client_ip
|
| 5 |
from db import (
|
| 6 |
+
ai_feedback_available,
|
| 7 |
fetch_live_messages,
|
| 8 |
fetch_opinion_change,
|
| 9 |
opinion_changes_available,
|
| 10 |
save_opinion_analysis,
|
| 11 |
+
save_opinion_feedback,
|
| 12 |
stance_available,
|
| 13 |
upsert_post_opinion,
|
| 14 |
upsert_pre_opinion,
|
| 15 |
)
|
| 16 |
from env import get_secret
|
| 17 |
+
from services.ai import build_feedback_prompt, build_opinion_change_prompt, generate_ai_response
|
| 18 |
|
| 19 |
|
| 20 |
_STANCE_OPTIONS = ["🔵 찬성", "🔴 반대"]
|
|
|
|
| 123 |
else:
|
| 124 |
final_stance_val = (row or {}).get("final_stance") or ""
|
| 125 |
discussion_conclusion_val = (row or {}).get("discussion_conclusion") or ""
|
| 126 |
+
ai_feedback = (row or {}).get("ai_feedback") or ""
|
| 127 |
if act_type == "토론" and final_stance_val:
|
| 128 |
st.success(f"✅ **최종 입장:** {final_stance_val}")
|
| 129 |
if act_type == "토의" and discussion_conclusion_val:
|
| 130 |
st.success(f"✅ **나의 결론:** {discussion_conclusion_val}")
|
| 131 |
st.success(f"✅ **토론 후 내 생각:** {post_opinion}")
|
| 132 |
st.divider()
|
| 133 |
+
|
| 134 |
+
# AI 피드백 카드
|
| 135 |
+
if ai_feedback and ai_feedback_available():
|
| 136 |
+
st.markdown("### 🌟 나의 AI 피드백 카드")
|
| 137 |
+
lines = ai_feedback.strip().splitlines()
|
| 138 |
+
well_lines, grow_lines = [], []
|
| 139 |
+
section = None
|
| 140 |
+
for line in lines:
|
| 141 |
+
if line.startswith("✅ 잘한 점"):
|
| 142 |
+
section = "well"
|
| 143 |
+
rest = line[len("✅ 잘한 점"):].lstrip(":").strip()
|
| 144 |
+
if rest:
|
| 145 |
+
well_lines.append(rest)
|
| 146 |
+
elif line.startswith("🌱 발전할 점"):
|
| 147 |
+
section = "grow"
|
| 148 |
+
rest = line[len("🌱 발전할 점"):].lstrip(":").strip()
|
| 149 |
+
if rest:
|
| 150 |
+
grow_lines.append(rest)
|
| 151 |
+
elif section == "well" and line.strip():
|
| 152 |
+
well_lines.append(line.strip())
|
| 153 |
+
elif section == "grow" and line.strip():
|
| 154 |
+
grow_lines.append(line.strip())
|
| 155 |
+
|
| 156 |
+
col_well, col_grow = st.columns(2)
|
| 157 |
+
with col_well:
|
| 158 |
+
st.success("**✅ 잘한 점**\n\n" + "\n\n".join(well_lines) if well_lines else "**✅ 잘한 점**\n\n(분석 중...)")
|
| 159 |
+
with col_grow:
|
| 160 |
+
st.warning("**🌱 발전할 점**\n\n" + "\n\n".join(grow_lines) if grow_lines else "**🌱 발전할 점**\n\n(분석 중...)")
|
| 161 |
+
st.divider()
|
| 162 |
+
|
| 163 |
if ai_analysis:
|
| 164 |
st.info("🤖 **AI 배움 분석**")
|
| 165 |
st.markdown(ai_analysis.replace("\n", "\n\n"))
|
|
|
|
| 211 |
else:
|
| 212 |
debate_history = "(토론 발언 기록 없음)"
|
| 213 |
|
| 214 |
+
api_key = get_secret("GEMINI_API_KEY", "")
|
| 215 |
+
|
| 216 |
with st.spinner("🤖 AI가 배움의 변화를 분석하고 있습니다..."):
|
| 217 |
+
# 배움 분석
|
| 218 |
prompt = build_opinion_change_prompt(
|
| 219 |
act_type, current_topic, student_name, pre_opinion, post_opinion, debate_history
|
| 220 |
)
|
| 221 |
res_text = generate_ai_response(
|
| 222 |
prompt,
|
| 223 |
model_name=AI_MODEL_NAME,
|
| 224 |
+
api_key=api_key,
|
| 225 |
log_message="AI 생각 변화 분석 실패",
|
| 226 |
room_name=room_name,
|
| 227 |
student=student_name,
|
| 228 |
)
|
| 229 |
if res_text:
|
| 230 |
save_opinion_analysis(supabase, room_name, student_name, res_text)
|
|
|
|
| 231 |
cache_key = f"img_{room_name}_{student_name}_bytes"
|
| 232 |
st.session_state.pop(cache_key, None)
|
| 233 |
+
|
| 234 |
+
# AI 피드백 카드 (잘한 점 / 발전할 점)
|
| 235 |
+
if ai_feedback_available():
|
| 236 |
+
feedback_prompt = build_feedback_prompt(act_type, current_topic, student_name, debate_history)
|
| 237 |
+
feedback_text = generate_ai_response(
|
| 238 |
+
feedback_prompt,
|
| 239 |
+
model_name=AI_MODEL_NAME,
|
| 240 |
+
api_key=api_key,
|
| 241 |
+
log_message="AI 피드백 카드 생성 실패",
|
| 242 |
+
room_name=room_name,
|
| 243 |
+
student=student_name,
|
| 244 |
+
)
|
| 245 |
+
if feedback_text:
|
| 246 |
+
save_opinion_feedback(supabase, room_name, student_name, feedback_text)
|
| 247 |
+
|
| 248 |
+
if res_text:
|
| 249 |
st.toast("✅ AI 분석 완료!", icon="🎉")
|
| 250 |
else:
|
| 251 |
st.toast("🚨 AI 분석에 실패했습니다.", icon="❌")
|
components/teacher_dashboard.py
CHANGED
|
@@ -4,7 +4,7 @@ import pandas as pd
|
|
| 4 |
import plotly.express as px
|
| 5 |
import streamlit as st
|
| 6 |
|
| 7 |
-
from db import delete_opinion_change, destroy_room_data, fetch_all_opinion_changes, fetch_debate_status, fetch_live_messages, opinion_changes_available, session_control_available, set_debate_status, stance_available
|
| 8 |
from utils import create_analysis_image
|
| 9 |
from components.opinion_change import _render_image_download, _STANCE_OPTIONS
|
| 10 |
from wordcloud import build_word_frequencies, build_circular_wordcloud_html
|
|
@@ -58,9 +58,10 @@ def _render_oc_section(supabase, room_name, act_type, current_topic, df_all):
|
|
| 58 |
st.rerun()
|
| 59 |
|
| 60 |
row = df_oc[df_oc["student_name"] == selected].iloc[0]
|
| 61 |
-
pre
|
| 62 |
-
post
|
| 63 |
-
ai
|
|
|
|
| 64 |
|
| 65 |
ip_raw = _s(row.get("ip_address"))
|
| 66 |
student_ip = ip_raw.replace(".0.0.", ".X.X.") if ip_raw else ""
|
|
@@ -91,6 +92,32 @@ def _render_oc_section(supabase, room_name, act_type, current_topic, df_all):
|
|
| 91 |
with col_post:
|
| 92 |
st.caption("🔄 토론 후 생각")
|
| 93 |
st.info(post)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
if ai:
|
| 95 |
st.caption("🤖 AI 배움 분석")
|
| 96 |
st.markdown(ai.replace("\n", "\n\n"))
|
|
|
|
| 4 |
import plotly.express as px
|
| 5 |
import streamlit as st
|
| 6 |
|
| 7 |
+
from db import ai_feedback_available, delete_opinion_change, destroy_room_data, fetch_all_opinion_changes, fetch_debate_status, fetch_live_messages, opinion_changes_available, session_control_available, set_debate_status, stance_available
|
| 8 |
from utils import create_analysis_image
|
| 9 |
from components.opinion_change import _render_image_download, _STANCE_OPTIONS
|
| 10 |
from wordcloud import build_word_frequencies, build_circular_wordcloud_html
|
|
|
|
| 58 |
st.rerun()
|
| 59 |
|
| 60 |
row = df_oc[df_oc["student_name"] == selected].iloc[0]
|
| 61 |
+
pre = _s(row.get("pre_opinion"), "(없음)")
|
| 62 |
+
post = _s(row.get("post_opinion"), "(없음)")
|
| 63 |
+
ai = _s(row.get("ai_analysis"), "")
|
| 64 |
+
ai_feedback = _s(row.get("ai_feedback"), "")
|
| 65 |
|
| 66 |
ip_raw = _s(row.get("ip_address"))
|
| 67 |
student_ip = ip_raw.replace(".0.0.", ".X.X.") if ip_raw else ""
|
|
|
|
| 92 |
with col_post:
|
| 93 |
st.caption("🔄 토론 후 생각")
|
| 94 |
st.info(post)
|
| 95 |
+
if ai_feedback and ai_feedback_available():
|
| 96 |
+
st.caption("🌟 AI 피드백 카드")
|
| 97 |
+
col_well, col_grow = st.columns(2)
|
| 98 |
+
lines = ai_feedback.strip().splitlines()
|
| 99 |
+
well_lines, grow_lines = [], []
|
| 100 |
+
section = None
|
| 101 |
+
for line in lines:
|
| 102 |
+
if line.startswith("✅ 잘한 점"):
|
| 103 |
+
section = "well"
|
| 104 |
+
rest = line[len("✅ 잘한 점"):].lstrip(":").strip()
|
| 105 |
+
if rest:
|
| 106 |
+
well_lines.append(rest)
|
| 107 |
+
elif line.startswith("🌱 발전할 점"):
|
| 108 |
+
section = "grow"
|
| 109 |
+
rest = line[len("🌱 발전할 점"):].lstrip(":").strip()
|
| 110 |
+
if rest:
|
| 111 |
+
grow_lines.append(rest)
|
| 112 |
+
elif section == "well" and line.strip():
|
| 113 |
+
well_lines.append(line.strip())
|
| 114 |
+
elif section == "grow" and line.strip():
|
| 115 |
+
grow_lines.append(line.strip())
|
| 116 |
+
with col_well:
|
| 117 |
+
st.success("**✅ 잘한 점**\n\n" + "\n\n".join(well_lines) if well_lines else "**✅ 잘한 점**\n\n(없음)")
|
| 118 |
+
with col_grow:
|
| 119 |
+
st.warning("**🌱 발전할 점**\n\n" + "\n\n".join(grow_lines) if grow_lines else "**🌱 발전할 점**\n\n(없음)")
|
| 120 |
+
|
| 121 |
if ai:
|
| 122 |
st.caption("🤖 AI 배움 분석")
|
| 123 |
st.markdown(ai.replace("\n", "\n\n"))
|
db.py
CHANGED
|
@@ -122,6 +122,7 @@ def check_schema_columns() -> dict:
|
|
| 122 |
("session_control.status", lambda: supabase.table("session_control").select("status").limit(1).execute()),
|
| 123 |
("likes.opinion_id", lambda: supabase.table("likes").select("opinion_id").limit(1).execute()),
|
| 124 |
("debate.depth_level", lambda: supabase.table("debate").select("depth_level").limit(1).execute()),
|
|
|
|
| 125 |
]
|
| 126 |
|
| 127 |
results = {}
|
|
@@ -171,6 +172,9 @@ def likes_available() -> bool:
|
|
| 171 |
def depth_level_available() -> bool:
|
| 172 |
return check_schema_columns().get("debate.depth_level", False)
|
| 173 |
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
# ==========================================
|
| 176 |
# [4] 방(topic) 관련 쿼리
|
|
@@ -471,6 +475,18 @@ def fetch_all_opinion_changes(supabase: Client, room_name: str):
|
|
| 471 |
return pd.DataFrame(res.data)
|
| 472 |
|
| 473 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
def save_opinion_analysis(supabase: Client, room_name: str, student_name: str, ai_analysis: str):
|
| 475 |
if not opinion_changes_available():
|
| 476 |
return None
|
|
|
|
| 122 |
("session_control.status", lambda: supabase.table("session_control").select("status").limit(1).execute()),
|
| 123 |
("likes.opinion_id", lambda: supabase.table("likes").select("opinion_id").limit(1).execute()),
|
| 124 |
("debate.depth_level", lambda: supabase.table("debate").select("depth_level").limit(1).execute()),
|
| 125 |
+
("opinion_changes.ai_feedback", lambda: supabase.table("opinion_changes").select("ai_feedback").limit(1).execute()),
|
| 126 |
]
|
| 127 |
|
| 128 |
results = {}
|
|
|
|
| 172 |
def depth_level_available() -> bool:
|
| 173 |
return check_schema_columns().get("debate.depth_level", False)
|
| 174 |
|
| 175 |
+
def ai_feedback_available() -> bool:
|
| 176 |
+
return check_schema_columns().get("opinion_changes.ai_feedback", False)
|
| 177 |
+
|
| 178 |
|
| 179 |
# ==========================================
|
| 180 |
# [4] 방(topic) 관련 쿼리
|
|
|
|
| 475 |
return pd.DataFrame(res.data)
|
| 476 |
|
| 477 |
|
| 478 |
+
def save_opinion_feedback(supabase: Client, room_name: str, student_name: str, ai_feedback: str):
|
| 479 |
+
if not ai_feedback_available():
|
| 480 |
+
return None
|
| 481 |
+
return execute_query(
|
| 482 |
+
supabase.table("opinion_changes")
|
| 483 |
+
.update({"ai_feedback": ai_feedback})
|
| 484 |
+
.eq("room_name", room_name)
|
| 485 |
+
.eq("student_name", student_name),
|
| 486 |
+
fail_message="AI 피드백 저장 실패",
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
def save_opinion_analysis(supabase: Client, room_name: str, student_name: str, ai_analysis: str):
|
| 491 |
if not opinion_changes_available():
|
| 492 |
return None
|
services/ai.py
CHANGED
|
@@ -51,6 +51,23 @@ def build_opinion_change_prompt(act_type, current_topic, student_name, pre_opini
|
|
| 51 |
)
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def build_depth_analysis_prompt(opinions: list) -> str:
|
| 55 |
"""
|
| 56 |
opinions: list of (id, content) tuples
|
|
|
|
| 51 |
)
|
| 52 |
|
| 53 |
|
| 54 |
+
def build_feedback_prompt(act_type: str, current_topic: str, student_name: str, debate_history: str) -> str:
|
| 55 |
+
return (
|
| 56 |
+
f"'{current_topic}' 주제의 고등학교 {act_type}에서 "
|
| 57 |
+
f"'{student_name}' 학생의 발언을 분석해 개인 피드백을 작성하세요.\n\n"
|
| 58 |
+
f"[발언 기록]\n{debate_history}\n\n"
|
| 59 |
+
"[출력 형식 - 반드시 그대로]\n"
|
| 60 |
+
"✅ 잘한 점: ...\n"
|
| 61 |
+
"🌱 발전할 점: ...\n\n"
|
| 62 |
+
"[규칙]\n"
|
| 63 |
+
"- 학생의 실제 발언을 근거로 구체적으로 작성하세요.\n"
|
| 64 |
+
"- 각 항목은 2~3문장으로 작성하세요.\n"
|
| 65 |
+
"- 긍정적이고 격려하는 톤으로 작성하세요.\n"
|
| 66 |
+
"- 제목/헤더(#,##), 불필요한 서론 없이 결과만 출력하세요.\n"
|
| 67 |
+
"- 발언이 없거나 부족하면 '발언 기록이 부족하여 분석이 어렵습니다.'라고만 출력하세요."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
def build_depth_analysis_prompt(opinions: list) -> str:
|
| 72 |
"""
|
| 73 |
opinions: list of (id, content) tuples
|