Rajarshi255 commited on
Commit
e7abbc9
·
verified ·
1 Parent(s): 38ee65d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -178
app.py CHANGED
@@ -8,11 +8,10 @@ from google.oauth2.service_account import Credentials
8
  from openai import OpenAI
9
 
10
  # =====================================================
11
- # CONFIGURATION
12
  # =====================================================
13
 
14
  BASE_DIR = os.getcwd()
15
-
16
  SPREADSHEET_ID = "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk"
17
  WORKSHEET_NAME = "Scores"
18
 
@@ -25,36 +24,24 @@ DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
25
  # =====================================================
26
 
27
  def _client():
28
- """
29
- Creates OpenAI-compatible DeepSeek client.
30
- """
31
  if not DEEPSEEK_API_KEY:
32
- raise ValueError("DEEPSEEK_API_KEY not set.")
33
  return OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
34
 
35
-
36
  def _strip_json(raw):
37
- """
38
- Removes markdown code fences from model output.
39
- """
40
  s = (raw or "").strip()
41
  if s.startswith("```"):
42
  s = s.strip("`")
43
  s = s.replace("json", "", 1).strip()
44
  return s
45
 
46
-
47
  # =====================================================
48
  # GRADING
49
  # =====================================================
50
 
51
  def build_prompt(pssg, qas):
52
- """
53
- Builds grading prompt.
54
- """
55
  return f"""
56
- You are a precise reading comprehension grader.
57
- Judge ONLY factual correctness based strictly on the passage.
58
  Be tolerant of paraphrasing.
59
  Return JSON:
60
  total_questions, correct_count, percent,
@@ -65,11 +52,7 @@ DATA:
65
  'qa_pairs': [{'question':q,'student_answer':a} for q,a in qas]}, indent=2)}
66
  """
67
 
68
-
69
  def grade_answers(pssg, qas):
70
- """
71
- Sends answers to LLM and returns parsed result.
72
- """
73
  client = _client()
74
 
75
  response = client.chat.completions.create(
@@ -81,24 +64,13 @@ def grade_answers(pssg, qas):
81
  ]
82
  )
83
 
84
- content = _strip_json(response.choices[0].message.content)
85
-
86
- try:
87
- return json.loads(content)
88
- except Exception:
89
- raise ValueError("Invalid JSON returned:\n" + content)
90
-
91
 
92
  # =====================================================
93
- # GRAMMAR CORRECTION (LIBERAL)
94
  # =====================================================
95
 
96
  def correct_english(sentence):
97
- """
98
- Corrects only grammar mistakes.
99
- Does not change meaning.
100
- Ignores spacing and capitalization.
101
- """
102
  client = _client()
103
 
104
  response = client.chat.completions.create(
@@ -113,15 +85,14 @@ def correct_english(sentence):
113
 
114
  return response.choices[0].message.content.strip()
115
 
 
 
116
 
117
  # =====================================================
118
  # FILE LOADING
119
  # =====================================================
120
 
121
  def load_passages_and_questions():
122
- """
123
- Loads pssg*.txt and qstn*.txt files.
124
- """
125
  passages = {}
126
  questions = {}
127
 
@@ -141,58 +112,28 @@ def load_passages_and_questions():
141
 
142
  return passages, questions
143
 
144
-
145
  # =====================================================
146
- # GOOGLE SHEETS
147
  # =====================================================
148
 
149
  def get_sheet():
150
- """
151
- Connects to Google Sheet.
152
- """
153
  service_account_json = os.environ.get("gcp_service_account")
154
- if not service_account_json:
155
- raise ValueError("gcp_service_account not set.")
156
-
157
- scope = ["https://www.googleapis.com/auth/spreadsheets"]
158
  creds = Credentials.from_service_account_info(
159
  json.loads(service_account_json),
160
- scopes=scope
161
  )
162
-
163
  gc = gspread.authorize(creds)
164
  return gc.open_by_key(SPREADSHEET_ID).worksheet(WORKSHEET_NAME)
165
 
166
-
167
- def save_result(name, grade, level,
168
- correct, total, percent,
169
- stars):
170
- """
171
- Saves result to sheet.
172
- """
173
  sheet = get_sheet()
174
-
175
- row = [
176
  datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"),
177
  name,
178
  grade,
179
- correct,
180
- total,
181
- f"{percent}%",
182
- stars,
183
- f"Level {level}"
184
- ]
185
-
186
- sheet.append_row(row, value_input_option="USER_ENTERED")
187
-
188
-
189
- # =====================================================
190
- # NORMALIZATION
191
- # =====================================================
192
-
193
- def normalize_text(text):
194
- return " ".join(text.lower().strip().split())
195
-
196
 
197
  # =====================================================
198
  # UI
@@ -200,7 +141,7 @@ def normalize_text(text):
200
 
201
  with gr.Blocks() as demo:
202
 
203
- gr.Markdown("# Adaptive Reading Comprehension")
204
 
205
  name = gr.Textbox(label="Student Name")
206
  grade = gr.Textbox(label="Class")
@@ -208,165 +149,175 @@ with gr.Blocks() as demo:
208
  start_btn = gr.Button("Start")
209
 
210
  level_display = gr.Markdown()
211
- passage_box = gr.Textbox(label="Passage", lines=15, interactive=False)
212
 
213
- question_boxes = []
214
- answer_boxes = []
 
215
 
216
  for i in range(4):
217
- question_boxes.append(gr.Markdown(visible=False))
218
- answer_boxes.append(gr.Textbox(label=f"Answer {i+1}", visible=False))
 
 
 
 
219
 
220
- submit_btn = gr.Button("Submit")
221
- result_box = gr.Markdown()
222
 
223
- # Session state
224
- session_level = gr.State(0)
225
- session_pointer = gr.State(0)
226
- session_indices = gr.State([])
227
- session_pssg = gr.State()
228
- session_questions = gr.State()
229
 
230
  # =====================================================
231
- # START SESSION
232
  # =====================================================
233
 
234
- def start_session(name, grade):
235
  passages, questions = load_passages_and_questions()
236
  indices = sorted(passages.keys())
237
 
238
  level = 0
239
  pointer = 0
240
- chunk_size = 3 + level
241
 
242
- selected = indices[pointer:pointer + chunk_size]
243
 
244
  pssg = "\n\n".join(passages[i] for i in selected)
245
 
246
  q_list = []
247
  for i in selected:
248
- if i in questions:
249
- q_list.extend(questions[i])
250
 
251
- question_updates = []
252
  for i in range(4):
253
  if i < len(q_list):
254
- question_updates.append(gr.update(value=q_list[i], visible=True))
255
- question_updates.append(gr.update(visible=True))
256
  else:
257
- question_updates.append(gr.update(visible=False))
258
- question_updates.append(gr.update(visible=False))
259
 
260
  return (
261
  f"### Level {level}",
262
  pssg,
263
- *question_updates,
264
  level,
265
- pointer + chunk_size,
266
  indices,
267
- pssg,
268
- q_list
269
  )
270
 
271
  start_btn.click(
272
  start_session,
273
- inputs=[name, grade],
274
- outputs=[level_display,
275
- passage_box] +
276
- [item for pair in zip(question_boxes, answer_boxes) for item in pair] +
277
- [session_level,
278
- session_pointer,
279
- session_indices,
280
- session_pssg,
281
- session_questions]
282
  )
283
 
284
  # =====================================================
285
- # SUBMIT
286
  # =====================================================
287
 
288
- def submit(name, grade,
289
- level, pointer, indices,
290
- pssg, questions,
291
- *answers):
 
 
 
 
 
 
 
292
 
293
- answers = list(answers[:len(questions)])
294
- qas = list(zip(questions, answers))
295
 
296
  result = grade_answers(pssg, qas)
297
 
298
- correct = result["correct_count"]
299
- total = result["total_questions"]
300
  percent = result["percent"]
 
301
 
302
- stars = 5 if percent >= 90 else 4 if percent >= 80 else 3 if percent >= 70 else 2 if percent >= 60 else 1 if percent >= 50 else 0
303
 
304
- if stars >= 4:
305
- level += 1
306
 
307
- save_result(name, grade, level, correct, total, percent, stars)
308
 
309
- chunk_size = 3 + level
310
- selected = indices[pointer:pointer + chunk_size]
 
 
 
 
 
 
311
 
312
- if not selected:
313
- return (
314
- "### Completed All Passages",
315
- "All passages finished.",
316
- *[gr.update(visible=False)]*8,
317
- level,
318
- pointer,
319
- indices,
320
- pssg,
321
- questions
322
- )
323
-
324
- passages, questions_dict = load_passages_and_questions()
325
-
326
- new_pssg = "\n\n".join(passages[i] for i in selected)
327
-
328
- new_q_list = []
329
- for i in selected:
330
- if i in questions_dict:
331
- new_q_list.extend(questions_dict[i])
332
 
333
- question_updates = []
334
- for i in range(4):
335
- if i < len(new_q_list):
336
- question_updates.append(gr.update(value=new_q_list[i], visible=True))
337
- question_updates.append(gr.update(visible=True))
338
- else:
339
- question_updates.append(gr.update(visible=False))
340
- question_updates.append(gr.update(visible=False))
341
 
342
  return (
343
- f"### Level {level}\nScore: {percent}%\nStars: {stars}",
344
- new_pssg,
345
- *question_updates,
346
- level,
347
- pointer + chunk_size,
348
- indices,
349
- new_pssg,
350
- new_q_list
351
  )
352
 
353
  submit_btn.click(
354
- submit,
355
- inputs=[name,
356
- grade,
357
- session_level,
358
- session_pointer,
359
- session_indices,
360
- session_pssg,
361
- session_questions] + answer_boxes,
362
- outputs=[level_display,
363
- passage_box] +
364
- [item for pair in zip(question_boxes, answer_boxes) for item in pair] +
365
- [session_level,
366
- session_pointer,
367
- session_indices,
368
- session_pssg,
369
- session_questions]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  )
371
 
372
  demo.launch()
 
8
  from openai import OpenAI
9
 
10
  # =====================================================
11
+ # CONFIG
12
  # =====================================================
13
 
14
  BASE_DIR = os.getcwd()
 
15
  SPREADSHEET_ID = "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk"
16
  WORKSHEET_NAME = "Scores"
17
 
 
24
  # =====================================================
25
 
26
  def _client():
 
 
 
27
  if not DEEPSEEK_API_KEY:
28
+ raise ValueError("DEEPSEEK_API_KEY missing.")
29
  return OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
30
 
 
31
  def _strip_json(raw):
 
 
 
32
  s = (raw or "").strip()
33
  if s.startswith("```"):
34
  s = s.strip("`")
35
  s = s.replace("json", "", 1).strip()
36
  return s
37
 
 
38
  # =====================================================
39
  # GRADING
40
  # =====================================================
41
 
42
  def build_prompt(pssg, qas):
 
 
 
43
  return f"""
44
+ Judge factual correctness strictly from passage.
 
45
  Be tolerant of paraphrasing.
46
  Return JSON:
47
  total_questions, correct_count, percent,
 
52
  'qa_pairs': [{'question':q,'student_answer':a} for q,a in qas]}, indent=2)}
53
  """
54
 
 
55
  def grade_answers(pssg, qas):
 
 
 
56
  client = _client()
57
 
58
  response = client.chat.completions.create(
 
64
  ]
65
  )
66
 
67
+ return json.loads(_strip_json(response.choices[0].message.content))
 
 
 
 
 
 
68
 
69
  # =====================================================
70
+ # LIBERAL GRAMMAR CHECK
71
  # =====================================================
72
 
73
  def correct_english(sentence):
 
 
 
 
 
74
  client = _client()
75
 
76
  response = client.chat.completions.create(
 
85
 
86
  return response.choices[0].message.content.strip()
87
 
88
+ def normalize(text):
89
+ return " ".join(text.lower().strip().split())
90
 
91
  # =====================================================
92
  # FILE LOADING
93
  # =====================================================
94
 
95
  def load_passages_and_questions():
 
 
 
96
  passages = {}
97
  questions = {}
98
 
 
112
 
113
  return passages, questions
114
 
 
115
  # =====================================================
116
+ # GOOGLE SAVE
117
  # =====================================================
118
 
119
  def get_sheet():
 
 
 
120
  service_account_json = os.environ.get("gcp_service_account")
 
 
 
 
121
  creds = Credentials.from_service_account_info(
122
  json.loads(service_account_json),
123
+ scopes=["https://www.googleapis.com/auth/spreadsheets"]
124
  )
 
125
  gc = gspread.authorize(creds)
126
  return gc.open_by_key(SPREADSHEET_ID).worksheet(WORKSHEET_NAME)
127
 
128
+ def save_final(name, grade, level, avg_star):
 
 
 
 
 
 
129
  sheet = get_sheet()
130
+ sheet.append_row([
 
131
  datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"),
132
  name,
133
  grade,
134
+ level,
135
+ avg_star
136
+ ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
  # =====================================================
139
  # UI
 
141
 
142
  with gr.Blocks() as demo:
143
 
144
+ gr.Markdown("# Adaptive Reading")
145
 
146
  name = gr.Textbox(label="Student Name")
147
  grade = gr.Textbox(label="Class")
 
149
  start_btn = gr.Button("Start")
150
 
151
  level_display = gr.Markdown()
152
+ passage_box = gr.Textbox(lines=12, interactive=False)
153
 
154
+ q_boxes = []
155
+ a_boxes = []
156
+ rewrite_boxes = []
157
 
158
  for i in range(4):
159
+ q_boxes.append(gr.Markdown(visible=False))
160
+ a_boxes.append(gr.Textbox(label=f"Answer {i+1}", visible=False))
161
+ rewrite_boxes.append(gr.Textbox(label=f"Rewrite {i+1}", visible=False))
162
+
163
+ submit_btn = gr.Button("Submit Answers")
164
+ bonus_btn = gr.Button("Submit Improved English", visible=False)
165
 
166
+ feedback_box = gr.Markdown()
 
167
 
168
+ # Session states
169
+ level_state = gr.State(0)
170
+ pointer_state = gr.State(0)
171
+ indices_state = gr.State([])
172
+ star_list_state = gr.State([])
173
+ corrected_state = gr.State([])
174
 
175
  # =====================================================
176
+ # START
177
  # =====================================================
178
 
179
+ def start_session(name):
180
  passages, questions = load_passages_and_questions()
181
  indices = sorted(passages.keys())
182
 
183
  level = 0
184
  pointer = 0
185
+ chunk = 3 + level
186
 
187
+ selected = indices[pointer:pointer+chunk]
188
 
189
  pssg = "\n\n".join(passages[i] for i in selected)
190
 
191
  q_list = []
192
  for i in selected:
193
+ q_list.extend(questions.get(i, []))
 
194
 
195
+ updates = []
196
  for i in range(4):
197
  if i < len(q_list):
198
+ updates.append(gr.update(value=q_list[i], visible=True))
199
+ updates.append(gr.update(value="", visible=True))
200
  else:
201
+ updates.append(gr.update(visible=False))
202
+ updates.append(gr.update(visible=False))
203
 
204
  return (
205
  f"### Level {level}",
206
  pssg,
207
+ *updates,
208
  level,
209
+ pointer+chunk,
210
  indices,
211
+ [],
212
+ []
213
  )
214
 
215
  start_btn.click(
216
  start_session,
217
+ inputs=[name],
218
+ outputs=[level_display, passage_box] +
219
+ [item for pair in zip(q_boxes, a_boxes) for item in pair] +
220
+ [level_state, pointer_state, indices_state, star_list_state, corrected_state]
 
 
 
 
 
221
  )
222
 
223
  # =====================================================
224
+ # SUBMIT ANSWERS
225
  # =====================================================
226
 
227
+ def submit_answers(name, grade, level, pointer, indices, star_list, *answers):
228
+
229
+ passages, questions = load_passages_and_questions()
230
+
231
+ current_chunk = indices[pointer-(3+level):pointer]
232
+
233
+ pssg = "\n\n".join(passages[i] for i in current_chunk)
234
+
235
+ q_list = []
236
+ for i in current_chunk:
237
+ q_list.extend(questions.get(i, []))
238
 
239
+ qas = list(zip(q_list, answers[:len(q_list)]))
 
240
 
241
  result = grade_answers(pssg, qas)
242
 
 
 
243
  percent = result["percent"]
244
+ stars = percent / 20 # 100% = 5 stars
245
 
246
+ star_list.append(stars)
247
 
248
+ feedback = f"### You earned {stars:.2f} ⭐ this round\n"
 
249
 
250
+ corrected = []
251
 
252
+ for d in result["details"]:
253
+ if d["is_correct"]:
254
+ corrected_sentence = correct_english(d["student_answer"])
255
+ feedback += f"\n✅ {d['question']}\nCorrect English: {corrected_sentence}\n"
256
+ corrected.append(corrected_sentence)
257
+ else:
258
+ feedback += f"\n❌ {d['question']}\nCorrect Answer: {d['reference_answer']}\n"
259
+ corrected.append(None)
260
 
261
+ # Clear answers
262
+ answer_updates = [gr.update(value="") for _ in range(4)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
+ # Show rewrite only for correct ones
265
+ rewrite_updates = [
266
+ gr.update(value="", visible=True) if corrected[i] else gr.update(visible=False)
267
+ for i in range(4)
268
+ ]
 
 
 
269
 
270
  return (
271
+ feedback,
272
+ *answer_updates,
273
+ *rewrite_updates,
274
+ star_list,
275
+ corrected
 
 
 
276
  )
277
 
278
  submit_btn.click(
279
+ submit_answers,
280
+ inputs=[name, grade, level_state, pointer_state, indices_state, star_list_state] + a_boxes,
281
+ outputs=[feedback_box] + a_boxes + rewrite_boxes + [star_list_state, corrected_state]
282
+ )
283
+
284
+ # =====================================================
285
+ # BONUS SUBMIT
286
+ # =====================================================
287
+
288
+ def submit_bonus(name, grade, level, pointer, indices, star_list, corrected, *rewrites):
289
+
290
+ bonus = 0
291
+ for i in range(len(corrected)):
292
+ if corrected[i] and normalize(rewrites[i]) == normalize(corrected[i]):
293
+ bonus += 0.5
294
+
295
+ if star_list:
296
+ star_list[-1] += bonus
297
+
298
+ # Load next chunk
299
+ chunk = 3 + level
300
+ selected = indices[pointer:pointer+chunk]
301
+
302
+ if not selected:
303
+ avg_star = sum(star_list) / len(star_list)
304
+ save_final(name, grade, level, round(avg_star,2))
305
+ return f"### Session Complete\nFinal Average ⭐: {avg_star:.2f}"
306
+
307
+ passages, questions = load_passages_and_questions()
308
+
309
+ pssg = "\n\n".join(passages[i] for i in selected)
310
+
311
+ q_list = []
312
+ for i in selected:
313
+ q_list.extend(questions.get(i, []))
314
+
315
+ return f"### Bonus earned: +{bonus} ⭐\nLoading next passage..."
316
+
317
+ bonus_btn.click(
318
+ submit_bonus,
319
+ inputs=[name, grade, level_state, pointer_state, indices_state, star_list_state, corrected_state] + rewrite_boxes,
320
+ outputs=feedback_box
321
  )
322
 
323
  demo.launch()