Toya0421 commited on
Commit
9d6390b
·
verified ·
1 Parent(s): b34e274

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -62
app.py CHANGED
@@ -26,7 +26,7 @@ levels = [1, 2, 3, 4, 5]
26
  _log_lock = threading.Lock()
27
 
28
  # =========================
29
- # ✅ ログ列(ユーザー指定序に固定
30
  # =========================
31
  LOG_COLUMNS = [
32
  "user_id",
@@ -45,9 +45,9 @@ def _new_session_state():
45
  return {
46
  "session_id": str(uuid.uuid4()),
47
  "used_passages": set(),
48
- "question_count": 0, # ✅ 採点済み(submit_result保存済み)の問題数
49
  "user_id": None,
50
- "action_log": [], # ✅ 1問の間の選択変更履歴(submit_resultにまとめて入れる
51
  }
52
 
53
  # --- ログ追記(CSVのみ・固定カラムで統一) ---
@@ -66,15 +66,9 @@ def log_to_csv(entry: dict):
66
  lineterminator="\n",
67
  )
68
 
69
- # --- イベントログ(start / select / submit / submit_result を記録)
70
- # ※CSVに出す列はLOG_COLUMNSのみに固定
71
  def log_event(state: dict, **kwargs):
72
  now = (datetime.utcnow() + timedelta(hours=9)).strftime("%Y-%m-%d %H:%M:%S")
73
- entry = {
74
- "time": now,
75
- "user_id": state.get("user_id"),
76
- **kwargs
77
- }
78
  log_to_csv(entry)
79
 
80
  # --- AIで問題生成 ---
@@ -118,7 +112,6 @@ Respond with one word: "Correct" or "Incorrect".
118
  )
119
  result = response.choices[0].message.content.strip().lower()
120
 
121
- # "incorrect" の中に "correct" が含まれるため順序が重要
122
  if re.search(r"\bincorrect\b", result):
123
  return False
124
  if re.search(r"\bcorrect\b", result):
@@ -134,7 +127,7 @@ def adaptive_test(prev_level, prev_correct):
134
  return levels[idx - 1]
135
  return prev_level
136
 
137
- # --- passage取得(used_passages は state から渡す) ---
138
  def get_passage(level, used_passages):
139
  subset = passages_df[passages_df["level"] == level]
140
  available = [pid for pid in subset["passage_id"] if pid not in used_passages]
@@ -144,9 +137,8 @@ def get_passage(level, used_passages):
144
  text = subset[subset["passage_id"] == passage_id]["text"].iloc[0]
145
  return passage_id, text
146
 
147
- # --- 開始ボタン動作(startログを残す) ---
148
  def start_test(student_id, state):
149
- # 新規開始時は常に初期化
150
  state = _new_session_state()
151
 
152
  if not student_id or student_id.strip() == "":
@@ -166,7 +158,7 @@ def start_test(student_id, state):
166
  question = generate_question(text)
167
  displayed_time = datetime.utcnow() + timedelta(hours=9)
168
 
169
- # ✅ startログ(表示された問題の情報を記録
170
  log_event(
171
  state,
172
  question_number=1,
@@ -184,53 +176,22 @@ def start_test(student_id, state):
184
  "", True, displayed_time.isoformat(), 1, state["user_id"]
185
  )
186
 
187
- # --- 選択肢変更イベント変更も全部、正確な情報付きでCSVに残す) ---
188
- def log_choice_change(choice, question_number, user_id, prev_level, question_text, passage_id, state):
189
  if not isinstance(state, dict):
190
  state = _new_session_state()
191
-
192
  if choice:
193
  t_iso = (datetime.utcnow() + timedelta(hours=9)).isoformat()
194
-
195
- # ✅ メモリ上の操作履歴(submit_resultにまとめて入れる)
196
- state["action_log"].append({
197
- "action": "choice",
198
- "choice": choice,
199
- "time": t_iso
200
- })
201
-
202
- # ✅ selectログ(どの問題での選択か分かるように埋める)
203
- log_event(
204
- state,
205
- question_number=question_number,
206
- reading_level=prev_level,
207
- passage_id=passage_id,
208
- question=question_text,
209
- choice=choice,
210
- correct=None,
211
- actions=None,
212
- )
213
  return state
214
 
215
- # --- 回答送信(submitログ + 結果ログ) ---
216
  def next_step(prev_level, user_answer, question_text, passage_text,
217
  displayed_time, question_number, user_id, passage_id, state):
218
 
219
  if not isinstance(state, dict):
220
  state = _new_session_state()
221
 
222
- # ✅ submitログ(ボタン押下ごとに必ず記録、未選択でも残す)
223
- log_event(
224
- state,
225
- question_number=question_number,
226
- reading_level=prev_level,
227
- passage_id=passage_id,
228
- question=question_text,
229
- choice=user_answer,
230
- correct=None,
231
- actions=None,
232
- )
233
-
234
  if not user_answer:
235
  return (
236
  state,
@@ -239,14 +200,12 @@ def next_step(prev_level, user_answer, question_text, passage_text,
239
  )
240
 
241
  submit_time = datetime.utcnow() + timedelta(hours=9)
242
-
243
- # ✅ 採点済み数を増やす(=この問題は確定)
244
  state["question_count"] += 1
245
 
246
  correct = check_answer_with_ai(passage_text, question_text, user_answer)
247
  new_level = adaptive_test(prev_level, correct)
248
 
249
- # ✅ submit_resultログ(採点結果 + その問題の選択変更履歴
250
  log_event(
251
  state,
252
  question_number=state["question_count"],
@@ -275,7 +234,7 @@ def next_step(prev_level, user_answer, question_text, passage_text,
275
  next_question = generate_question(next_text)
276
  next_display_time = datetime.utcnow() + timedelta(hours=9)
277
 
278
- # ✅ 次の問題のために選択操作ログをリセット
279
  state["action_log"] = []
280
 
281
  feedback = "✅ Correct!" if correct else "❌ Incorrect."
@@ -287,7 +246,7 @@ def next_step(prev_level, user_answer, question_text, passage_text,
287
  None, "", True, next_display_time.isoformat(), state["question_count"] + 1, user_id, next_passage_id
288
  )
289
 
290
- # --- 管理者DL(再起動までの logs.csv を返す) ---
291
  def download_logs(admin_password):
292
  if not ADMIN_PASSWORD:
293
  return None, "⚠️ ADMIN_PASSWORD が設定されていません(環境変数で設定してください)"
@@ -299,7 +258,6 @@ def download_logs(admin_password):
299
  if not os.path.exists(LOG_FILE):
300
  return None, "⚠️ logs.csv がまだ存在しません(ログが1件もありません)"
301
 
302
- # DL安定のため一時コピーして返す
303
  tmp_dir = tempfile.mkdtemp()
304
  out_path = os.path.join(tmp_dir, "logs.csv")
305
  with open(LOG_FILE, "rb") as fsrc, open(out_path, "wb") as fdst:
@@ -311,7 +269,6 @@ def download_logs(admin_password):
311
  with gr.Blocks() as demo:
312
  gr.Markdown("# 📘 Reading Level Test")
313
 
314
- # ✅ セッションごとの状態
315
  session_state = gr.State(_new_session_state())
316
 
317
  student_id_input = gr.Textbox(label="Student ID", placeholder="例: B123456")
@@ -325,7 +282,7 @@ with gr.Blocks() as demo:
325
  feedback_display = gr.Markdown()
326
 
327
  hidden_level = gr.Number(visible=False)
328
- hidden_passage = gr.Textbox(visible=False) # 互換用に残す(未使用)
329
  hidden_display_time = gr.Textbox(visible=False)
330
  hidden_question_number = gr.Number(visible=False)
331
  hidden_user_id = gr.Textbox(visible=False)
@@ -343,14 +300,13 @@ with gr.Blocks() as demo:
343
  ]
344
  )
345
 
346
- # ✅ 選択肢変更ログ(変更も全部残す・正確な情報付き)
347
  user_answer.change(
348
  fn=log_choice_change,
349
- inputs=[user_answer, hidden_question_number, hidden_user_id, hidden_level, question_display, hidden_passage_id, session_state],
350
  outputs=[session_state]
351
  )
352
 
353
- # ✅ 回答送信(submitログ + submit_resultログ)
354
  submit_btn.click(
355
  fn=next_step,
356
  inputs=[hidden_level, user_answer, question_display, text_display,
@@ -363,7 +319,6 @@ with gr.Blocks() as demo:
363
  ]
364
  )
365
 
366
- # ✅ 表示のON/OFF制御
367
  def toggle_visibility(show):
368
  v = bool(show)
369
  return (
 
26
  _log_lock = threading.Lock()
27
 
28
  # =========================
29
+ # ✅ ログ列(指定順)
30
  # =========================
31
  LOG_COLUMNS = [
32
  "user_id",
 
45
  return {
46
  "session_id": str(uuid.uuid4()),
47
  "used_passages": set(),
48
+ "question_count": 0, # ✅ 採点済み問題数
49
  "user_id": None,
50
+ "action_log": [], # ✅ 1問の選択変更履歴(submit時にまとめて保存
51
  }
52
 
53
  # --- ログ追記(CSVのみ・固定カラムで統一) ---
 
66
  lineterminator="\n",
67
  )
68
 
 
 
69
  def log_event(state: dict, **kwargs):
70
  now = (datetime.utcnow() + timedelta(hours=9)).strftime("%Y-%m-%d %H:%M:%S")
71
+ entry = {"time": now, "user_id": state.get("user_id"), **kwargs}
 
 
 
 
72
  log_to_csv(entry)
73
 
74
  # --- AIで問題生成 ---
 
112
  )
113
  result = response.choices[0].message.content.strip().lower()
114
 
 
115
  if re.search(r"\bincorrect\b", result):
116
  return False
117
  if re.search(r"\bcorrect\b", result):
 
127
  return levels[idx - 1]
128
  return prev_level
129
 
130
+ # --- passage取得 ---
131
  def get_passage(level, used_passages):
132
  subset = passages_df[passages_df["level"] == level]
133
  available = [pid for pid in subset["passage_id"] if pid not in used_passages]
 
137
  text = subset[subset["passage_id"] == passage_id]["text"].iloc[0]
138
  return passage_id, text
139
 
140
+ # --- 開始ボタン動作(start時だけログ) ---
141
  def start_test(student_id, state):
 
142
  state = _new_session_state()
143
 
144
  if not student_id or student_id.strip() == "":
 
158
  question = generate_question(text)
159
  displayed_time = datetime.utcnow() + timedelta(hours=9)
160
 
161
+ # ✅ startログ(choice/correct/actionsは空
162
  log_event(
163
  state,
164
  question_number=1,
 
176
  "", True, displayed_time.isoformat(), 1, state["user_id"]
177
  )
178
 
179
+ # --- 選択肢変更(CSVには書かない。actionsにだけ溜める) ---
180
+ def log_choice_change(choice, question_number, user_id, state):
181
  if not isinstance(state, dict):
182
  state = _new_session_state()
 
183
  if choice:
184
  t_iso = (datetime.utcnow() + timedelta(hours=9)).isoformat()
185
+ state["action_log"].append({"action": "choice", "choice": choice, "time": t_iso})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  return state
187
 
188
+ # --- 回答送信(submit時だけログ) ---
189
  def next_step(prev_level, user_answer, question_text, passage_text,
190
  displayed_time, question_number, user_id, passage_id, state):
191
 
192
  if not isinstance(state, dict):
193
  state = _new_session_state()
194
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  if not user_answer:
196
  return (
197
  state,
 
200
  )
201
 
202
  submit_time = datetime.utcnow() + timedelta(hours=9)
 
 
203
  state["question_count"] += 1
204
 
205
  correct = check_answer_with_ai(passage_text, question_text, user_answer)
206
  new_level = adaptive_test(prev_level, correct)
207
 
208
+ # ✅ submitログ(ここだけ記録
209
  log_event(
210
  state,
211
  question_number=state["question_count"],
 
234
  next_question = generate_question(next_text)
235
  next_display_time = datetime.utcnow() + timedelta(hours=9)
236
 
237
+ # ✅ 次の問題のために選択変更履歴をリセット
238
  state["action_log"] = []
239
 
240
  feedback = "✅ Correct!" if correct else "❌ Incorrect."
 
246
  None, "", True, next_display_time.isoformat(), state["question_count"] + 1, user_id, next_passage_id
247
  )
248
 
249
+ # --- 管理者DL ---
250
  def download_logs(admin_password):
251
  if not ADMIN_PASSWORD:
252
  return None, "⚠️ ADMIN_PASSWORD が設定されていません(環境変数で設定してください)"
 
258
  if not os.path.exists(LOG_FILE):
259
  return None, "⚠️ logs.csv がまだ存在しません(ログが1件もありません)"
260
 
 
261
  tmp_dir = tempfile.mkdtemp()
262
  out_path = os.path.join(tmp_dir, "logs.csv")
263
  with open(LOG_FILE, "rb") as fsrc, open(out_path, "wb") as fdst:
 
269
  with gr.Blocks() as demo:
270
  gr.Markdown("# 📘 Reading Level Test")
271
 
 
272
  session_state = gr.State(_new_session_state())
273
 
274
  student_id_input = gr.Textbox(label="Student ID", placeholder="例: B123456")
 
282
  feedback_display = gr.Markdown()
283
 
284
  hidden_level = gr.Number(visible=False)
285
+ hidden_passage = gr.Textbox(visible=False) # 互換用(未使用)
286
  hidden_display_time = gr.Textbox(visible=False)
287
  hidden_question_number = gr.Number(visible=False)
288
  hidden_user_id = gr.Textbox(visible=False)
 
300
  ]
301
  )
302
 
303
+ # ✅ 選択肢変更はCSVに書かず、actionsにだけ溜める
304
  user_answer.change(
305
  fn=log_choice_change,
306
+ inputs=[user_answer, hidden_question_number, hidden_user_id, session_state],
307
  outputs=[session_state]
308
  )
309
 
 
310
  submit_btn.click(
311
  fn=next_step,
312
  inputs=[hidden_level, user_answer, question_display, text_display,
 
319
  ]
320
  )
321
 
 
322
  def toggle_visibility(show):
323
  v = bool(show)
324
  return (