MisConceptTutor / MisconceptTutor.py
Jintonic92's picture
Upload MisconceptTutor.py
6085a05 verified
raw
history blame
18.5 kB
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):
# """μœ μ‚¬ 문제 생성"""
# if not isinstance(wrong_q, dict):
# logger.error(f"Invalid wrong_q type: {type(wrong_q)}")
# st.error("μœ μ‚¬ 문제 생성에 ν•„μš”ν•œ 데이터 ν˜•μ‹μ΄ 잘λͺ»λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
# return None
# try:
# generated_q, _ = generator.generate_similar_question_with_text(
# construct_name=wrong_q['ConstructName'],
# subject_name=wrong_q['SubjectName'],
# question_text=wrong_q['QuestionText'],
# correct_answer_text=wrong_q[f'Answer{wrong_q["CorrectAnswer"]}Text'],
# wrong_answer_text=wrong_q[f'Answer{st.session_state.selected_wrong_answer}Text'],
# misconception_id=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 generating similar question: {e}")
# st.error(f"문제 생성 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.")
# return None
# def generate_similar_question(wrong_q, misconception_id, generator):
# """μœ μ‚¬ 문제 생성"""
# # μž…λ ₯ 데이터 확인
# logger.info(f"Generating similar question for misconception_id: {misconception_id}")
# logger.info(f"Wrong question data type: {type(wrong_q)}")
# logger.info(f"Wrong question data: {wrong_q}")
# # wrong_qκ°€ λ”•μ…”λ„ˆλ¦¬κ°€ μ•„λ‹Œ 경우 처리
# if not isinstance(wrong_q, dict):
# logger.error(f"Invalid wrong_q type: {type(wrong_q)}")
# st.error("μœ μ‚¬ 문제 생성에 ν•„μš”ν•œ 데이터 ν˜•μ‹μ΄ 잘λͺ»λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
# return None
# # misconception_id NaN 체크
# if pd.isna(misconception_id):
# logger.warning("misconception_id 값이 NaNμž…λ‹ˆλ‹€. κΈ°λ³Έ 문제λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.")
# return {
# 'question': f"[μœ μ‚¬ 문제] {wrong_q.get('QuestionText', 'λ¬Έμ œκ°€ μ œκ³΅λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.')}",
# 'choices': {
# 'A': "보기 A",
# 'B': "보기 B",
# 'C': "보기 C",
# 'D': "보기 D"
# },
# 'correct': 'A',
# 'explanation': "Misconception IDκ°€ μ œκ³΅λ˜μ§€ μ•Šμ•„ κΈ°λ³Έ 문제λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€."
# }
# try:
# # μœ μ‚¬ 문제 생성
# #logger.info(f"At least I'm in")
# #logger.info(f"Type of wrong_q: {type(wrong_q)}")
# #logger.info(f"Content of wrong_q: {wrong_q}")
# #logger.info(f"Type of misconception_id: {type(misconception_id)}")
# #logger.info(f"Value of misconception_id: {misconception_id}")
# # input 정리
# construct_name=wrong_q['ConstructName'],
# subject_name=wrong_q['SubjectName'],
# question_text=wrong_q['QuestionText'],
# correct_answer_text=wrong_q[f'Answer{wrong_q["CorrectAnswer"]}Text'],
# wrong_answer_text=wrong_q[f'Answer{st.session_state.selected_wrong_answer}Text'],
# misconception_id=int(misconception_id)
# #logger.info(f"Input Arguments: construct_name={construct_name}, subject_name={subject_name}, question_text={question_text}, correct_answer_text={correct_answer_text}, wrong_answer_text={wrong_answer_text}, misconception_id={misconception_id}")
# construct_name = construct_name[0] if isinstance(construct_name, tuple) else construct_name
# subject_name = subject_name[0] if isinstance(subject_name, tuple) else subject_name
# question_text = question_text[0] if isinstance(question_text, tuple) else question_text
# correct_answer_text = correct_answer_text[0] if isinstance(correct_answer_text, tuple) else correct_answer_text
# wrong_answer_text = wrong_answer_text[0] if isinstance(wrong_answer_text, tuple) else wrong_answer_text
# #logger.info(f"construct_name={construct_name}, Type={type(construct_name)}, subject_name={subject_name}, Type={type(subject_name)}")
# #logger.info(f"question_text={question_text}, Type={type(question_text)}, correct_answer_text={correct_answer_text}, Type={type(correct_answer_text)}")
# #logger.info(f"wrong_answer_text={wrong_answer_text}, Type={type(wrong_answer_text)}")
# print("Debugging log block reached")
# #logger.info(f"Cleaned Input Arguments: construct_name={construct_name}, subject_name={subject_name}, question_text={question_text}, correct_answer_text={correct_answer_text}, wrong_answer_text={wrong_answer_text}, misconception_id={misconception_id}")
# #logger.debug(f"Cleaned arguments: {construct_name}, {subject_name}, {question_text}, {correct_answer_text}, {wrong_answer_text}, {misconception_id}")
# # generated_q, _ = generator.generate_similar_question_with_text(
# # construct_name=wrong_q['ConstructName'],
# # subject_name=wrong_q['SubjectName'],
# # question_text=wrong_q['QuestionText'],
# # correct_answer_text=wrong_q[f'Answer{wrong_q["CorrectAnswer"]}Text'],
# # wrong_answer_text=wrong_q[f'Answer{st.session_state.selected_wrong_answer}Text'],
# # misconception_id=int(misconception_id)
# # )
# logger.info(f"Inputs: construct_name={construct_name}, subject_name={subject_name}, question_text={question_text}, correct_answer_text={correct_answer_text}, wrong_answer_text={wrong_answer_text}, misconception_id={misconception_id}")
# generated_q, _ = generator.generate_similar_question_with_text(
# construct_name,
# subject_name,
# question_text,
# correct_answer_text,
# wrong_answer_text,
# misconception_id
# )
# logger.info(f"Generated question type: {type(generated_q)}")
# if generated_q:
# logger.info(f"At least there is something generated")
# 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 generating similar question: {e}")
# st.error(f"문제 생성 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. {e}")
# return None
# # κΈ°λ³Έ 문제 λ°˜ν™˜
# return {
# 'question': f"[μœ μ‚¬ 문제] {wrong_q.get('QuestionText', 'λ¬Έμ œκ°€ μ œκ³΅λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.')}",
# 'choices': {
# 'A': "μƒˆλ‘œμš΄ 보기 A",
# 'B': "μƒˆλ‘œμš΄ 보기 B",
# 'C': "μƒˆλ‘œμš΄ 보기 C",
# 'D': "μƒˆλ‘œμš΄ 보기 D"
# },
# 'correct': 'A',
# 'explanation': f"이 λ¬Έμ œλŠ” Misconception ID {misconception_id}와 κ΄€λ ¨λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€."
# }
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 정보가 μ—†μŠ΅λ‹ˆλ‹€.")
# try:
# misconception_text = generator.get_misconception_text(misconception_id)
# st.info(f"Misconception ID: {int(misconception_id)}\n\n{misconception_text}")
# except Exception as e:
# logger.error(f"Error in get_misconception_text: {e}")
# st.info("Misconception 정보가 μ—†μŠ΅λ‹ˆλ‹€.")
# return None, None
# μœ μ‚¬ 문제 생성 λ²„νŠΌ
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 __name__ == "__main__":
main()
# random_state 42μ—μ„œ μ •λ‹΅
# D C A A C
# A B B B B