Spaces:
Sleeping
Sleeping
File size: 20,604 Bytes
99d03e3 0a8c581 99d03e3 52a539a 0a8c581 52a539a 99d03e3 0a8c581 59f9aef 0a8c581 82850bb 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 1c13954 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 1c13954 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 0a8c581 52a539a 41ddd8a fec1647 0a8c581 fec1647 52a539a 41ddd8a fec1647 41ddd8a fec1647 41ddd8a fec1647 41ddd8a fec1647 41ddd8a fec1647 41ddd8a fec1647 41ddd8a fec1647 41ddd8a fec1647 52a539a fec1647 0a8c581 52a539a |
1 2 3 4 5 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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
import streamlit as st
import pandas as pd
import os
from src.SecondModule.module2 import SimilarQuestionGenerator
import logging
from typing import Optional, Tuple
logging.basicConfig(level=logging.DEBUG)
# Streamlit νμ΄μ§ κΈ°λ³Έ μ€μ
st.set_page_config(
page_title="MisconcepTutor",
layout="wide",
initial_sidebar_state="expanded"
)
# κ²½λ‘ μ€μ
base_path = os.path.dirname(os.path.abspath(__file__))
data_path = os.path.join(base_path, 'Data')
misconception_csv_path = os.path.join(data_path, 'misconception_mapping.csv')
# λ‘κΉ
μ€μ
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# μΈμ
μν μ΄κΈ°ν - κ°μ₯ λ¨Όμ μ€νλλλ‘ μ΅μλ¨μ λ°°μΉ
if 'initialized' not in st.session_state:
st.session_state.initialized = True
st.session_state.wrong_questions = []
st.session_state.misconceptions = []
st.session_state.current_question_index = 0
st.session_state.generated_questions = []
st.session_state.current_step = 'initial'
st.session_state.selected_wrong_answer = None
st.session_state.questions = []
logger.info("Session state initialized")
# λ¬Έμ μμ±κΈ° μ΄κΈ°ν
@st.cache_resource
def load_question_generator():
"""λ¬Έμ μμ± λͺ¨λΈ λ‘λ"""
if not os.path.exists(misconception_csv_path):
st.error(f"CSV νμΌμ΄ μ‘΄μ¬νμ§ μμ΅λλ€: {misconception_csv_path}")
raise FileNotFoundError(f"CSV νμΌμ΄ μ‘΄μ¬νμ§ μμ΅λλ€: {misconception_csv_path}")
return SimilarQuestionGenerator(misconception_csv_path=misconception_csv_path)
# CSV λ°μ΄ν° λ‘λ ν¨μ
@st.cache_data
def load_data(data_file = '/train.csv'):
try:
file_path = os.path.join(data_path, data_file.lstrip('/'))
df = pd.read_csv(file_path)
logger.info(f"Data loaded successfully from {file_path}")
return df
except FileNotFoundError:
st.error(f"νμΌμ μ°Ύμ μ μμ΅λλ€: {data_file}")
logger.error(f"File not found: {data_file}")
return None
def start_quiz():
"""ν΄μ¦ μμ λ° μ΄κΈ°ν"""
df = load_data()
if df is None or df.empty:
st.error("λ°μ΄ν°λ₯Ό λΆλ¬μ¬ μ μμ΅λλ€. λ°μ΄ν°μ
μ νμΈν΄μ£ΌμΈμ.")
return
st.session_state.questions = df.sample(n=10, random_state=42)
st.session_state.current_step = 'quiz'
st.session_state.current_question_index = 0
st.session_state.wrong_questions = []
st.session_state.misconceptions = []
st.session_state.generated_questions = []
logger.info("Quiz started")
def generate_similar_question(wrong_q, misconception_id, generator):
"""μ μ¬ λ¬Έμ μμ±"""
logger.info(f"Generating similar question for misconception_id: {misconception_id}")
# μ
λ ₯ λ°μ΄ν° μ ν¨μ± κ²μ¬
if not isinstance(wrong_q, dict):
logger.error(f"Invalid wrong_q type: {type(wrong_q)}")
st.error("μ μ¬ λ¬Έμ μμ±μ νμν λ°μ΄ν° νμμ΄ μλͺ»λμμ΅λλ€.")
return None
# misconception_idκ° μ ν¨νμ§ νμΈ
if pd.isna(misconception_id):
logger.warning("misconception_id is NaN")
return None
try:
# λ°μ΄ν° μ€λΉ (νν λ³ν λ°©μ§)
input_data = {
'construct_name': str(wrong_q.get('ConstructName', '')),
'subject_name': str(wrong_q.get('SubjectName', '')),
'question_text': str(wrong_q.get('QuestionText', '')),
'correct_answer_text': str(wrong_q.get(f'Answer{wrong_q["CorrectAnswer"]}Text', '')),
'wrong_answer_text': str(wrong_q.get(f'Answer{st.session_state.selected_wrong_answer}Text', '')),
'misconception_id': int(misconception_id)
}
logger.info(f"Prepared input data: {input_data}")
# μ μ¬ λ¬Έμ μμ± νΈμΆ
generated_q, _ = generator.generate_similar_question_with_text(
construct_name=input_data['construct_name'],
subject_name=input_data['subject_name'],
question_text=input_data['question_text'],
correct_answer_text=input_data['correct_answer_text'],
wrong_answer_text=input_data['wrong_answer_text'],
misconception_id=input_data['misconception_id']
)
if generated_q:
return {
'question': generated_q.question,
'choices': generated_q.choices,
'correct': generated_q.correct_answer,
'explanation': generated_q.explanation
}
except Exception as e:
logger.error(f"Error in generate_similar_question: {str(e)}")
st.error(f"λ¬Έμ μμ± μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}")
return None
return None
def handle_answer(answer, current_q):
"""λ΅λ³ μ²λ¦¬"""
if answer != current_q['CorrectAnswer']:
wrong_q_dict = current_q.to_dict()
st.session_state.wrong_questions.append(wrong_q_dict)
st.session_state.selected_wrong_answer = answer
misconception_key = f'Misconception{answer}Id'
misconception_id = current_q.get(misconception_key)
st.session_state.misconceptions.append(misconception_id)
st.session_state.current_question_index += 1
if st.session_state.current_question_index >= 10:
st.session_state.current_step = 'review'
def main():
"""λ©μΈ μ ν리μΌμ΄μ
λ‘μ§"""
st.title("MisconcepTutor")
# Generator μ΄κΈ°ν
generator = load_question_generator()
# μ΄κΈ° νλ©΄
if st.session_state.current_step == 'initial':
st.write("#### νμ΅μ μμνκ² μ΅λλ€. 10κ°μ λ¬Έμ λ₯Ό νμ΄λ³ΌκΉμ?")
if st.button("νμ΅ μμ", key="start_quiz"):
start_quiz()
st.rerun()
# ν΄μ¦ νλ©΄
elif st.session_state.current_step == 'quiz':
current_q = st.session_state.questions.iloc[st.session_state.current_question_index]
# μ§ν μν© νμ
progress = st.session_state.current_question_index / 10
st.progress(progress)
st.write(f"### λ¬Έμ {st.session_state.current_question_index + 1}/10")
# λ¬Έμ νμ
st.markdown("---")
st.write(current_q['QuestionText'])
# 보기 νμ
col1, col2 = st.columns(2)
with col1:
if st.button(f"A) {current_q['AnswerAText']}", key="A"):
handle_answer('A', current_q)
st.rerun()
if st.button(f"C) {current_q['AnswerCText']}", key="C"):
handle_answer('C', current_q)
st.rerun()
with col2:
if st.button(f"B) {current_q['AnswerBText']}", key="B"):
handle_answer('B', current_q)
st.rerun()
if st.button(f"D) {current_q['AnswerDText']}", key="D"):
handle_answer('D', current_q)
st.rerun()
# λ³΅μ΅ νλ©΄
elif st.session_state.current_step == 'review':
st.write("### νμ΅ κ²°κ³Ό")
# κ²°κ³Ό ν΅κ³
col1, col2, col3 = st.columns(3)
col1.metric("μ΄ λ¬Έμ μ", 10)
col2.metric("λ§μ λ¬Έμ ", 10 - len(st.session_state.wrong_questions))
col3.metric("νλ¦° λ¬Έμ ", len(st.session_state.wrong_questions))
# κ²°κ³Όμ λ°λ₯Έ λ©μμ§ νμ
if len(st.session_state.wrong_questions) == 0:
st.balloons() # μΆν ν¨κ³Ό
st.success("π μΆνν©λλ€! λͺ¨λ λ¬Έμ λ₯Ό λ§μΆμ
¨μ΄μ!")
st.markdown("""
### π μνμμ΄μλλ€!
μλ²½ν μ μλ₯Ό λ°μΌμ
¨λ€μ! μνμ κ°λ
μ μ ννκ² μ΄ν΄νκ³ κ³μ κ² κ°μ΅λλ€.
""")
elif len(st.session_state.wrong_questions) <= 3:
st.success("μ νμ
¨μ΄μ! μ‘°κΈλ§ λ μ°μ΅νλ©΄ μλ²½ν κ±°μμ!")
else:
st.info("μ²μ²ν κ°λ
μ 볡μ΅ν΄λ³΄μμ. μ°μ΅νλ€ λ³΄λ©΄ λμ΄λ κ±°μμ!")
# λ€λΉκ²μ΄μ
λ²νΌ
col1, col2 = st.columns(2)
with col1:
if st.button("π μλ‘μ΄ λ¬Έμ μΈνΈ μμνκΈ°", use_container_width=True):
start_quiz()
st.rerun()
with col2:
if st.button("π μ²μμΌλ‘ λμκ°κΈ°", use_container_width=True):
st.session_state.clear()
st.rerun()
# νλ¦° λ¬Έμ λΆμ
if st.session_state.wrong_questions:
st.write("### βοΈ νλ¦° λ¬Έμ λΆμ")
for i, (wrong_q, misconception_id) in enumerate(zip(
st.session_state.wrong_questions,
st.session_state.misconceptions
)):
with st.expander(f"π νλ¦° λ¬Έμ #{i + 1}"):
st.write("**π λ¬Έμ :**")
st.write(wrong_q['QuestionText'])
st.write("**β
μ λ΅:**", wrong_q['CorrectAnswer'])
st.write("---")
st.write("**π κ΄λ ¨λ Misconception:**")
if misconception_id and not pd.isna(misconception_id):
misconception_text = generator.get_misconception_text(misconception_id)
st.info(f"Misconception ID: {int(misconception_id)}\n\n{misconception_text}")
else:
st.info("Misconception μ λ³΄κ° μμ΅λλ€.")
# # μ μ¬ λ¬Έμ μμ± λ²νΌ
# if st.button(f"π μ μ¬ λ¬Έμ νκΈ° #{i + 1}", key=f"retry_{i}"):
# with st.spinner("μ μ¬ λ¬Έμ λ₯Ό μμ±νκ³ μμ΅λλ€..."):
# logger.info(f"Generating similar question for misconception_id: {misconception_id}")
# new_question = generate_similar_question(wrong_q, misconception_id, generator)
# if new_question:
# st.write("### π― μ μ¬ λ¬Έμ ")
# st.write(new_question['question'])
# st.write("**보기:**")
# for choice, text in new_question['choices'].items():
# st.write(f"{choice}) {text}")
# st.write("**β
μ λ΅:**", new_question['correct'])
# st.write("**π ν΄μ€:**", new_question['explanation'])
# else:
# st.error("μ μ¬ λ¬Έμ λ₯Ό μμ±ν μ μμ΅λλ€.")
# # μ μ¬ λ¬Έμ μμ± λ²νΌ
# if st.button(f"π μ μ¬ λ¬Έμ νκΈ° #{i + 1}", key=f"retry_{i}"):
# with st.spinner("μ μ¬ λ¬Έμ λ₯Ό μμ±νκ³ μμ΅λλ€..."):
# logger.info(f"Generating similar question for misconception_id: {misconception_id}")
# new_question = generate_similar_question(wrong_q, misconception_id, generator)
# if new_question:
# st.write("### π― μ μ¬ λ¬Έμ ")
# st.write(new_question['question'])
# # μ λ΅μ μΈμ
μ€ν
μ΄νΈμ μ μ₯
# if f"similar_question_answered_{i}" not in st.session_state:
# st.session_state[f"similar_question_answered_{i}"] = False
# if f"similar_question_correct_{i}" not in st.session_state:
# st.session_state[f"similar_question_correct_{i}"] = new_question['correct']
# # μμ§ λ΅λ³νμ§ μμ κ²½μ°μλ§ λ³΄κΈ° λ²νΌ νμ
# if not st.session_state[f"similar_question_answered_{i}"]:
# st.write("**보기:**")
# col1, col2 = st.columns(2)
# with col1:
# if st.button(f"A) {new_question['choices']['A']}", key=f"similar_A_{i}"):
# st.session_state[f"similar_question_answered_{i}"] = True
# if 'A' == new_question['correct']:
# st.success("β
μ λ΅μ
λλ€!")
# else:
# st.error("β νλ Έμ΅λλ€.")
# st.rerun()
# if st.button(f"C) {new_question['choices']['C']}", key=f"similar_C_{i}"):
# st.session_state[f"similar_question_answered_{i}"] = True
# if 'C' == new_question['correct']:
# st.success("β
μ λ΅μ
λλ€!")
# else:
# st.error("β νλ Έμ΅λλ€.")
# st.rerun()
# with col2:
# if st.button(f"B) {new_question['choices']['B']}", key=f"similar_B_{i}"):
# st.session_state[f"similar_question_answered_{i}"] = True
# if 'B' == new_question['correct']:
# st.success("β
μ λ΅μ
λλ€!")
# else:
# st.error("β νλ Έμ΅λλ€.")
# st.rerun()
# if st.button(f"D) {new_question['choices']['D']}", key=f"similar_D_{i}"):
# st.session_state[f"similar_question_answered_{i}"] = True
# if 'D' == new_question['correct']:
# st.success("β
μ λ΅μ
λλ€!")
# else:
# st.error("β νλ Έμ΅λλ€.")
# st.rerun()
# # λ΅λ³ν κ²½μ° κ²°κ³Ό λ° ν΄μ€ νμ
# if st.session_state[f"similar_question_answered_{i}"]:
# st.write("---")
# st.write("**π ν΄μ€:**", new_question['explanation'])
# # λ€μ νκΈ° λ²νΌ
# if st.button("π λ€μ νκΈ°", key=f"reset_{i}"):
# st.session_state[f"similar_question_answered_{i}"] = False
# st.rerun()
# else:
# st.error("μ μ¬ λ¬Έμ λ₯Ό μμ±ν μ μμ΅λλ€.")
# νλ¦° λ¬Έμ λΆμ λΆλΆμμ
if st.button(f"π μ μ¬ λ¬Έμ νκΈ° #{i + 1}", key=f"retry_{i}"):
# μ μ¬ λ¬Έμ μμ± μνλ₯Ό μΈμ
μ μ μ₯
st.session_state[f"show_similar_question_{i}"] = True
st.session_state[f"similar_question_answered_{i}"] = False
# κΈ°μ‘΄ λ΅λ³ κΈ°λ‘ μ΄κΈ°ν
st.rerun()
# μ μ¬ λ¬Έμ κ° μμ±λ μνμΈ κ²½μ°
if st.session_state.get(f"show_similar_question_{i}", False):
with st.spinner("μ μ¬ λ¬Έμ λ₯Ό μμ±νκ³ μμ΅λλ€..."):
new_question = generate_similar_question(wrong_q, misconception_id, generator)
if new_question:
st.write("### π― μ μ¬ λ¬Έμ ")
st.write(new_question['question'])
# λ΅λ³ μν νμΈ
answered = st.session_state.get(f"similar_question_answered_{i}", False)
selected_answer = st.session_state.get(f"selected_answer_{i}", None)
# 보기 νμ
st.write("**보기:**")
col1, col2 = st.columns(2)
# λ΅λ³νμ§ μμ κ²½μ°μλ§ λ²νΌ νμ±ν
if not answered:
with col1:
for option in ['A', 'C']:
if st.button(
f"{option}) {new_question['choices'][option]}",
key=f"similar_{option}_{i}"
):
st.session_state[f"similar_question_answered_{i}"] = True
st.session_state[f"selected_answer_{i}"] = option
st.rerun()
with col2:
for option in ['B', 'D']:
if st.button(
f"{option}) {new_question['choices'][option]}",
key=f"similar_{option}_{i}"
):
st.session_state[f"similar_question_answered_{i}"] = True
st.session_state[f"selected_answer_{i}"] = option
st.rerun()
# λ΅λ³ν κ²½μ° κ²°κ³Ό νμ
if answered:
selected = st.session_state[f"selected_answer_{i}"]
if selected == new_question['correct']:
st.success("β
μ λ΅μ
λλ€!")
else:
st.error(f"β νλ Έμ΅λλ€. μ λ΅μ {new_question['correct']}μ
λλ€.")
# ν΄μ€ νμ
st.write("---")
st.write("**π ν΄μ€:**", new_question['explanation'])
# λ€μ νκΈ° λ²νΌ
if st.button("π λ€μ νκΈ°", key=f"reset_{i}"):
st.session_state[f"similar_question_answered_{i}"] = False
st.session_state[f"selected_answer_{i}"] = None
st.rerun()
# λ¬Έμ λ«κΈ° λ²νΌ
if st.button("β λ¬Έμ λ«κΈ°", key=f"close_{i}"):
st.session_state[f"show_similar_question_{i}"] = False
st.rerun()
else:
st.error("μ μ¬ λ¬Έμ λ₯Ό μμ±ν μ μμ΅λλ€.")
if st.button("β λ«κΈ°", key=f"close_error_{i}"):
st.session_state[f"show_similar_question_{i}"] = False
st.rerun()
if __name__ == "__main__":
main()
# random_state 42μμ μ λ΅
# D C A A C
# A B B B B
|