Jintonic92 commited on
Commit
d0fa913
·
verified ·
1 Parent(s): 0a8c581

Delete MisconceptTutor.py

Browse files
Files changed (1) hide show
  1. MisconceptTutor.py +0 -404
MisconceptTutor.py DELETED
@@ -1,404 +0,0 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import os
4
- from src.SecondModule.module2 import SimilarQuestionGenerator
5
- import logging
6
- from typing import Optional, Tuple
7
- logging.basicConfig(level=logging.DEBUG)
8
-
9
-
10
- # Streamlit 페이지 기본 설정
11
- st.set_page_config(
12
- page_title="MisconcepTutor",
13
- layout="wide",
14
- initial_sidebar_state="expanded"
15
- )
16
-
17
- # 경로 설정
18
- base_path = os.path.dirname(os.path.abspath(__file__))
19
- data_path = os.path.join(base_path, 'Data')
20
- misconception_csv_path = os.path.join(data_path, 'misconception_mapping.csv')
21
-
22
- # 로깅 설정
23
- logging.basicConfig(level=logging.INFO)
24
- logger = logging.getLogger(__name__)
25
-
26
- # 세션 상태 초기화 - 가장 먼저 실행되도록 최상단에 배치
27
- if 'initialized' not in st.session_state:
28
- st.session_state.initialized = True
29
- st.session_state.wrong_questions = []
30
- st.session_state.misconceptions = []
31
- st.session_state.current_question_index = 0
32
- st.session_state.generated_questions = []
33
- st.session_state.current_step = 'initial'
34
- st.session_state.selected_wrong_answer = None
35
- st.session_state.questions = []
36
- logger.info("Session state initialized")
37
-
38
- # 문제 생성기 초기화
39
- @st.cache_resource
40
- def load_question_generator():
41
- """문제 생성 모델 로드"""
42
- if not os.path.exists(misconception_csv_path):
43
- st.error(f"CSV 파일이 존재하지 않습니다: {misconception_csv_path}")
44
- raise FileNotFoundError(f"CSV 파일이 존재하지 않습니다: {misconception_csv_path}")
45
- return SimilarQuestionGenerator(misconception_csv_path=misconception_csv_path)
46
-
47
- # CSV 데이터 로드 함수
48
- @st.cache_data
49
- def load_data(data_file = '/train.csv'):
50
- try:
51
- file_path = os.path.join(data_path, data_file.lstrip('/'))
52
- df = pd.read_csv(file_path)
53
- logger.info(f"Data loaded successfully from {file_path}")
54
- return df
55
- except FileNotFoundError:
56
- st.error(f"파일을 찾을 수 없습니다: {data_file}")
57
- logger.error(f"File not found: {data_file}")
58
- return None
59
-
60
- def start_quiz():
61
- """퀴즈 시작 및 초기화"""
62
- df = load_data()
63
- if df is None or df.empty:
64
- st.error("데이터를 불러올 수 없습니다. 데이터셋을 확인해주세요.")
65
- return
66
-
67
- st.session_state.questions = df.sample(n=10, random_state=42)
68
- st.session_state.current_step = 'quiz'
69
- st.session_state.current_question_index = 0
70
- st.session_state.wrong_questions = []
71
- st.session_state.misconceptions = []
72
- st.session_state.generated_questions = []
73
- logger.info("Quiz started")
74
-
75
- # def generate_similar_question(wrong_q, misconception_id, generator):
76
- # """유사 문제 생성"""
77
- # if not isinstance(wrong_q, dict):
78
- # logger.error(f"Invalid wrong_q type: {type(wrong_q)}")
79
- # st.error("유사 문제 생성에 필요한 데이터 형식이 잘못되었습니다.")
80
- # return None
81
-
82
- # try:
83
- # generated_q, _ = generator.generate_similar_question_with_text(
84
- # construct_name=wrong_q['ConstructName'],
85
- # subject_name=wrong_q['SubjectName'],
86
- # question_text=wrong_q['QuestionText'],
87
- # correct_answer_text=wrong_q[f'Answer{wrong_q["CorrectAnswer"]}Text'],
88
- # wrong_answer_text=wrong_q[f'Answer{st.session_state.selected_wrong_answer}Text'],
89
- # misconception_id=misconception_id
90
- # )
91
-
92
- # if generated_q:
93
- # return {
94
- # 'question': generated_q.question,
95
- # 'choices': generated_q.choices,
96
- # 'correct': generated_q.correct_answer,
97
- # 'explanation': generated_q.explanation
98
- # }
99
- # except Exception as e:
100
- # logger.error(f"Error generating similar question: {e}")
101
- # st.error(f"문제 생성 중 오류가 발생했습니다.")
102
- # return None
103
-
104
- # def generate_similar_question(wrong_q, misconception_id, generator):
105
- # """유사 문제 생성"""
106
- # # 입력 데이터 확인
107
- # logger.info(f"Generating similar question for misconception_id: {misconception_id}")
108
- # logger.info(f"Wrong question data type: {type(wrong_q)}")
109
- # logger.info(f"Wrong question data: {wrong_q}")
110
-
111
- # # wrong_q가 딕셔너리가 아닌 경우 처리
112
- # if not isinstance(wrong_q, dict):
113
- # logger.error(f"Invalid wrong_q type: {type(wrong_q)}")
114
- # st.error("유사 문제 생성에 필요한 데이터 형식이 잘못되었습니다.")
115
- # return None
116
-
117
- # # misconception_id NaN 체크
118
- # if pd.isna(misconception_id):
119
- # logger.warning("misconception_id 값이 NaN입니다. 기본 문제를 반환합니다.")
120
- # return {
121
- # 'question': f"[유사 문제] {wrong_q.get('QuestionText', '문제가 제공되지 않았습니다.')}",
122
- # 'choices': {
123
- # 'A': "보기 A",
124
- # 'B': "보기 B",
125
- # 'C': "보기 C",
126
- # 'D': "보기 D"
127
- # },
128
- # 'correct': 'A',
129
- # 'explanation': "Misconception ID가 제공되지 않아 기본 문제를 반환합니다."
130
- # }
131
-
132
- # try:
133
- # # 유사 문제 생성
134
- # #logger.info(f"At least I'm in")
135
-
136
- # #logger.info(f"Type of wrong_q: {type(wrong_q)}")
137
- # #logger.info(f"Content of wrong_q: {wrong_q}")
138
- # #logger.info(f"Type of misconception_id: {type(misconception_id)}")
139
- # #logger.info(f"Value of misconception_id: {misconception_id}")
140
-
141
-
142
- # # input 정리
143
- # construct_name=wrong_q['ConstructName'],
144
- # subject_name=wrong_q['SubjectName'],
145
- # question_text=wrong_q['QuestionText'],
146
- # correct_answer_text=wrong_q[f'Answer{wrong_q["CorrectAnswer"]}Text'],
147
- # wrong_answer_text=wrong_q[f'Answer{st.session_state.selected_wrong_answer}Text'],
148
- # misconception_id=int(misconception_id)
149
- # #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}")
150
-
151
- # construct_name = construct_name[0] if isinstance(construct_name, tuple) else construct_name
152
- # subject_name = subject_name[0] if isinstance(subject_name, tuple) else subject_name
153
- # question_text = question_text[0] if isinstance(question_text, tuple) else question_text
154
- # correct_answer_text = correct_answer_text[0] if isinstance(correct_answer_text, tuple) else correct_answer_text
155
- # wrong_answer_text = wrong_answer_text[0] if isinstance(wrong_answer_text, tuple) else wrong_answer_text
156
- # #logger.info(f"construct_name={construct_name}, Type={type(construct_name)}, subject_name={subject_name}, Type={type(subject_name)}")
157
- # #logger.info(f"question_text={question_text}, Type={type(question_text)}, correct_answer_text={correct_answer_text}, Type={type(correct_answer_text)}")
158
- # #logger.info(f"wrong_answer_text={wrong_answer_text}, Type={type(wrong_answer_text)}")
159
- # print("Debugging log block reached")
160
-
161
- # #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}")
162
- # #logger.debug(f"Cleaned arguments: {construct_name}, {subject_name}, {question_text}, {correct_answer_text}, {wrong_answer_text}, {misconception_id}")
163
-
164
- # # generated_q, _ = generator.generate_similar_question_with_text(
165
- # # construct_name=wrong_q['ConstructName'],
166
- # # subject_name=wrong_q['SubjectName'],
167
- # # question_text=wrong_q['QuestionText'],
168
- # # correct_answer_text=wrong_q[f'Answer{wrong_q["CorrectAnswer"]}Text'],
169
- # # wrong_answer_text=wrong_q[f'Answer{st.session_state.selected_wrong_answer}Text'],
170
- # # misconception_id=int(misconception_id)
171
- # # )
172
- # 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}")
173
-
174
- # generated_q, _ = generator.generate_similar_question_with_text(
175
- # construct_name,
176
- # subject_name,
177
- # question_text,
178
- # correct_answer_text,
179
- # wrong_answer_text,
180
- # misconception_id
181
- # )
182
- # logger.info(f"Generated question type: {type(generated_q)}")
183
-
184
- # if generated_q:
185
- # logger.info(f"At least there is something generated")
186
- # return {
187
- # 'question': generated_q.question,
188
- # 'choices': generated_q.choices,
189
- # 'correct': generated_q.correct_answer,
190
- # 'explanation': generated_q.explanation
191
- # }
192
- # except Exception as e:
193
- # # 디버깅을 위한 상세 오류 출력
194
- # logger.error(f"Error generating similar question: {e}")
195
- # st.error(f"문제 생성 중 오류가 발생했습니다. {e}")
196
- # return None
197
-
198
- # # 기본 문제 반환
199
- # return {
200
- # 'question': f"[유사 문제] {wrong_q.get('QuestionText', '문제가 제공되지 않았습니다.')}",
201
- # 'choices': {
202
- # 'A': "새로운 보기 A",
203
- # 'B': "새로운 보기 B",
204
- # 'C': "새로운 보기 C",
205
- # 'D': "새로운 보기 D"
206
- # },
207
- # 'correct': 'A',
208
- # 'explanation': f"이 문제는 Misconception ID {misconception_id}와 관련되어 있습니다."
209
- # }
210
-
211
- def generate_similar_question(wrong_q, misconception_id, generator):
212
- """유사 문제 생성"""
213
- logger.info(f"Generating similar question for misconception_id: {misconception_id}")
214
-
215
- # 입력 데이터 유효성 검사
216
- if not isinstance(wrong_q, dict):
217
- logger.error(f"Invalid wrong_q type: {type(wrong_q)}")
218
- st.error("유사 문제 생성에 필요한 데이터 형식이 잘못되었습니다.")
219
- return None
220
-
221
- # misconception_id가 유효한지 확인
222
- if pd.isna(misconception_id):
223
- logger.warning("misconception_id is NaN")
224
- return None
225
-
226
- try:
227
- # 데이터 준비 (튜플 변환 방지)
228
- input_data = {
229
- 'construct_name': str(wrong_q.get('ConstructName', '')),
230
- 'subject_name': str(wrong_q.get('SubjectName', '')),
231
- 'question_text': str(wrong_q.get('QuestionText', '')),
232
- 'correct_answer_text': str(wrong_q.get(f'Answer{wrong_q["CorrectAnswer"]}Text', '')),
233
- 'wrong_answer_text': str(wrong_q.get(f'Answer{st.session_state.selected_wrong_answer}Text', '')),
234
- 'misconception_id': int(misconception_id)
235
- }
236
-
237
- logger.info(f"Prepared input data: {input_data}")
238
-
239
- # 유사 문제 생성 호출
240
- generated_q, _ = generator.generate_similar_question_with_text(
241
- construct_name=input_data['construct_name'],
242
- subject_name=input_data['subject_name'],
243
- question_text=input_data['question_text'],
244
- correct_answer_text=input_data['correct_answer_text'],
245
- wrong_answer_text=input_data['wrong_answer_text'],
246
- misconception_id=input_data['misconception_id']
247
- )
248
-
249
- if generated_q:
250
- return {
251
- 'question': generated_q.question,
252
- 'choices': generated_q.choices,
253
- 'correct': generated_q.correct_answer,
254
- 'explanation': generated_q.explanation
255
- }
256
-
257
- except Exception as e:
258
- logger.error(f"Error in generate_similar_question: {str(e)}")
259
- st.error(f"문제 생성 중 오류가 발생했습니다: {str(e)}")
260
- return None
261
-
262
- return None
263
-
264
- def handle_answer(answer, current_q):
265
- """답변 처리"""
266
- if answer != current_q['CorrectAnswer']:
267
- wrong_q_dict = current_q.to_dict()
268
- st.session_state.wrong_questions.append(wrong_q_dict)
269
- st.session_state.selected_wrong_answer = answer
270
-
271
- misconception_key = f'Misconception{answer}Id'
272
- misconception_id = current_q.get(misconception_key)
273
- st.session_state.misconceptions.append(misconception_id)
274
-
275
- st.session_state.current_question_index += 1
276
- if st.session_state.current_question_index >= 10:
277
- st.session_state.current_step = 'review'
278
-
279
- def main():
280
- """메인 애플리케이션 로직"""
281
- st.title("MisconcepTutor")
282
-
283
- # Generator 초기화
284
- generator = load_question_generator()
285
-
286
- # 초기 화면
287
- if st.session_state.current_step == 'initial':
288
- st.write("#### 학습을 시작하겠습니다. 10개의 문제를 풀어볼까요?")
289
- if st.button("학습 시작", key="start_quiz"):
290
- start_quiz()
291
- st.rerun()
292
-
293
- # 퀴즈 화면
294
- elif st.session_state.current_step == 'quiz':
295
- current_q = st.session_state.questions.iloc[st.session_state.current_question_index]
296
-
297
- # 진행 상황 표시
298
- progress = st.session_state.current_question_index / 10
299
- st.progress(progress)
300
- st.write(f"### 문제 {st.session_state.current_question_index + 1}/10")
301
-
302
- # 문제 표시
303
- st.markdown("---")
304
- st.write(current_q['QuestionText'])
305
-
306
- # 보기 표시
307
- col1, col2 = st.columns(2)
308
- with col1:
309
- if st.button(f"A) {current_q['AnswerAText']}", key="A"):
310
- handle_answer('A', current_q)
311
- st.rerun()
312
- if st.button(f"C) {current_q['AnswerCText']}", key="C"):
313
- handle_answer('C', current_q)
314
- st.rerun()
315
- with col2:
316
- if st.button(f"B) {current_q['AnswerBText']}", key="B"):
317
- handle_answer('B', current_q)
318
- st.rerun()
319
- if st.button(f"D) {current_q['AnswerDText']}", key="D"):
320
- handle_answer('D', current_q)
321
- st.rerun()
322
-
323
- # 복습 화면
324
- elif st.session_state.current_step == 'review':
325
- st.write("### 학습 결과")
326
-
327
- # 결과 통계
328
- col1, col2, col3 = st.columns(3)
329
- col1.metric("총 문제 수", 10)
330
- col2.metric("맞은 문제", 10 - len(st.session_state.wrong_questions))
331
- col3.metric("틀린 문제", len(st.session_state.wrong_questions))
332
-
333
- # 결과에 따른 메시지 표시
334
- if len(st.session_state.wrong_questions) == 0:
335
- st.balloons() # 축하 효과
336
- st.success("🎉 축하합니다! 모든 문제를 맞추셨어요!")
337
- st.markdown("""
338
- ### 🏆 수학왕이십니다!
339
- 완벽한 점수를 받으셨네요! 수학적 개념을 정확하게 이해하고 계신 것 같습��다.
340
- """)
341
- elif len(st.session_state.wrong_questions) <= 3:
342
- st.success("잘 하셨어요! 조금만 더 연습하면 완벽할 거예요!")
343
- else:
344
- st.info("천천히 개념을 복습해보아요. 연습하다 보면 늘어날 거예요!")
345
-
346
- # 네비게이션 버튼
347
- col1, col2 = st.columns(2)
348
- with col1:
349
- if st.button("🔄 새로운 문제 세트 시작하기", use_container_width=True):
350
- start_quiz()
351
- st.rerun()
352
- with col2:
353
- if st.button("🏠 처음으로 돌아가기", use_container_width=True):
354
- st.session_state.clear()
355
- st.rerun()
356
-
357
- # 틀린 문제 분석
358
- if st.session_state.wrong_questions:
359
- st.write("### ✍️ 틀린 문제 분석")
360
- for i, (wrong_q, misconception_id) in enumerate(zip(
361
- st.session_state.wrong_questions,
362
- st.session_state.misconceptions
363
- )):
364
- with st.expander(f"📝 틀린 문제 #{i + 1}"):
365
- st.write("**📋 문제:**")
366
- st.write(wrong_q['QuestionText'])
367
- st.write("**✅ 정답:**", wrong_q['CorrectAnswer'])
368
-
369
- st.write("---")
370
- st.write("**🔍 관련된 Misconception:**")
371
- if misconception_id and not pd.isna(misconception_id):
372
- misconception_text = generator.get_misconception_text(misconception_id)
373
- st.info(f"Misconception ID: {int(misconception_id)}\n\n{misconception_text}")
374
- else:
375
- st.info("Misconception 정보가 없습니다.")
376
- # try:
377
- # misconception_text = generator.get_misconception_text(misconception_id)
378
- # st.info(f"Misconception ID: {int(misconception_id)}\n\n{misconception_text}")
379
- # except Exception as e:
380
- # logger.error(f"Error in get_misconception_text: {e}")
381
- # st.info("Misconception 정보가 없습니다.")
382
- # return None, None
383
-
384
- # 유사 문제 생성 버튼
385
- if st.button(f"📚 유사 문제 풀기 #{i + 1}", key=f"retry_{i}"):
386
- with st.spinner("유사 문제를 생성하고 있습니다..."):
387
- logger.info(f"Generating similar question for misconception_id: {misconception_id}")
388
- new_question = generate_similar_question(wrong_q, misconception_id, generator)
389
- if new_question:
390
- st.write("### 🎯 유사 문제")
391
- st.write(new_question['question'])
392
- st.write("**보기:**")
393
- for choice, text in new_question['choices'].items():
394
- st.write(f"{choice}) {text}")
395
- st.write("**✅ 정답:**", new_question['correct'])
396
- st.write("**📝 해설:**", new_question['explanation'])
397
- else:
398
- st.error("유사 문제를 생성할 수 없습니다.")
399
- if __name__ == "__main__":
400
- main()
401
-
402
- # random_state 42에서 정답
403
- # D C A A C
404
- # A B B B B