abhidgp1978 commited on
Commit
0a2dfeb
·
verified ·
1 Parent(s): 9edd93a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -34
app.py CHANGED
@@ -52,6 +52,7 @@ def call_groq_api(prompt: str, temperature: float = 0.3, max_tokens: int = 512)
52
  # ----------------------------
53
 
54
  def read_remote_records() -> List[Dict[str, Any]]:
 
55
  try:
56
  local_path = hf_hub_download(repo_id=REPO_ID, filename=FILE_NAME, repo_type=REPO_TYPE, token=HF_WRITE_TOKEN)
57
  with open(local_path, "r", encoding="utf-8") as f:
@@ -123,6 +124,7 @@ def parse_questions(text: str) -> List[str]:
123
 
124
 
125
  def generate_answer_key(questions_text: str, subject: str, grade: str) -> str:
 
126
  prompt = (
127
  "You are an expert K-12 teacher creating an answer key.\n"
128
  "Given the following homework questions (a numbered list), produce a matching answer key as a numbered list, "
@@ -137,6 +139,7 @@ def generate_answer_key(questions_text: str, subject: str, grade: str) -> str:
137
  # ----------------------------
138
 
139
  def grade_with_llm(questions: List[str], answers: List[str], answer_key_text: str, min_attention: int) -> Tuple[str, bool, List[Dict[str, Any]]]:
 
140
  qa_pairs = []
141
  for i, q in enumerate(questions, start=1):
142
  a = answers[i-1] if i-1 < len(answers) else ""
@@ -147,9 +150,8 @@ def grade_with_llm(questions: List[str], answers: List[str], answer_key_text: st
147
  "Return STRICT JSON with this schema: {\n"
148
  " \"items\": [ { \"i\": number, \"score\": 0|1, \"feedback\": string } ... ],\n"
149
  " \"total\": number, \"out_of\": number, \"needs_attention\": boolean\n}\n\n"
150
- "Use these to grade concisely.\n\n"
151
  f"Answer Key:\n{answer_key_text}\n\n"
152
- f"Questions + Student Answers (array of objects):\n{json.dumps(qa_pairs, ensure_ascii=False)}\n\n"
153
  "Now output ONLY the JSON object, no extra commentary."
154
  )
155
 
@@ -161,35 +163,33 @@ def grade_with_llm(questions: List[str], answers: List[str], answer_key_text: st
161
  data = json.loads(blob)
162
  total = int(data.get("total", 0))
163
  out_of = int(data.get("out_of", len(questions)))
164
- needs_attention = total < min_attention if min_attention > 0 else bool(data.get("needs_attention", total < 0.6 * out_of))
165
  items = data.get("items", [])
166
  except Exception:
167
  total = sum(1 for a in answers if a.strip())
168
  out_of = len(questions)
169
- needs_attention = total < min_attention if min_attention > 0 else total < 0.6 * out_of
170
  items = [{"i": i+1, "score": 1 if (i < len(answers) and answers[i].strip()) else 0, "feedback": ""} for i in range(out_of)]
171
 
172
  summary = f"Score: {total}/{out_of}."
173
  return summary, needs_attention, items
174
 
175
  # ----------------------------
176
- # Filtering helpers
177
  # ----------------------------
178
 
179
  def filter_homework_names(subject: str, grade: str) -> List[str]:
180
  records = read_remote_records()
181
  filtered = [r for r in records if r.get("record_type") == "homework" and r.get("subject") == subject and r.get("grade") == grade]
182
  names = [r.get("homework_name", "Unnamed Homework") for r in filtered]
183
- names = list(dict.fromkeys(names))
184
  return names
185
 
186
-
187
  def get_homework_records(subject: str, grade: str, homework_name: str) -> List[Dict[str, Any]]:
188
  records = read_remote_records()
189
  matches = [r for r in records if r.get("record_type") == "homework" and r.get("subject") == subject and r.get("grade") == grade and r.get("homework_name") == homework_name]
190
  return matches
191
 
192
-
193
  def get_submission_records(subject: str, grade: str, homework_name: str) -> List[Dict[str, Any]]:
194
  records = read_remote_records()
195
  matches = [r for r in records if r.get("record_type") == "submission" and r.get("subject") == subject and r.get("grade") == grade and r.get("homework_name") == homework_name]
@@ -208,6 +208,9 @@ with gr.Blocks() as demo:
208
  min_attention_state = gr.State(0)
209
 
210
  with gr.Tabs():
 
 
 
211
  with gr.TabItem("Teacher"):
212
  with gr.Row():
213
  with gr.Column(scale=1):
@@ -218,15 +221,12 @@ with gr.Blocks() as demo:
218
  homework_name_in = gr.Textbox(label="Homework Name (e.g., Homework 1)")
219
  complexity_in = gr.Dropdown(label="Complexity", choices=["Easy", "Medium", "Hard"], value="Medium")
220
  brief_in = gr.Textbox(label="Homework Brief (describe topic & grade)", lines=4)
221
-
222
- question_count = gr.Dropdown(
223
  label="Number of Questions",
224
- choices=[str(i) for i in range(1, 11)],
225
- value="10",
226
- interactive=True,
227
  )
228
- gr.Markdown("Options beyond 10 are Pro only.")
229
-
230
  gen_btn = gr.Button("Generate Homework", variant="primary")
231
 
232
  with gr.Column(scale=1):
@@ -238,10 +238,9 @@ with gr.Blocks() as demo:
238
  status = gr.Textbox(label="Status / Logs", interactive=False)
239
 
240
  gr.Markdown("### Review Submissions")
241
- min_attention_input = gr.Number(label="Minimum Attention Marks (Threshold)", value=0)
242
-
243
  with gr.Row():
244
  with gr.Column(scale=1):
 
245
  review_subject = gr.Dropdown(label="Subject", choices=["Mathematics","Science","English","History","Geography","Other"], value="Mathematics")
246
  review_grade = gr.Dropdown(label="Grade", choices=[f"Grade {i}" for i in range(1,13)], value="Grade 5")
247
  review_hw_name = gr.Dropdown(label="Select Homework", choices=[], value=None, interactive=True)
@@ -250,20 +249,14 @@ with gr.Blocks() as demo:
250
  submissions_table = gr.Dataframe(headers=["Timestamp","Student","Score","Needs Attention","Details"], row_count=0, col_count=5, wrap=True)
251
  submission_json = gr.JSON(label="Selected Homework: Raw Submissions JSON", visible=False)
252
 
253
- def on_generate(name, email, subject, grade, hw_name, complexity, brief, q_count):
254
- if not brief.strip():
255
- return "Please enter a brief"
256
- num_questions = int(q_count)
257
- return generate_homework(subject, brief, num_questions=num_questions, complexity=complexity)
258
 
259
  def on_generate_answer_key(questions_text, subject, grade):
260
- if not questions_text.strip():
261
- return "Please generate or paste questions first."
262
  return generate_answer_key(questions_text, subject, grade)
263
 
264
  def on_save_homework(name, email, subject, grade, hw_name, complexity, brief, questions_text, answer_key_text):
265
- if not hw_name.strip():
266
- return "Please enter a homework name"
267
  rec = {
268
  "record_type": "homework",
269
  "id": str(uuid.uuid4()),
@@ -288,30 +281,30 @@ with gr.Blocks() as demo:
288
  return gr.update(choices=names, interactive=True, value=names[0])
289
 
290
  def build_submissions_table(subject, grade, hw_name, min_attention):
291
- if not hw_name:
292
- return [], []
293
- subs = get_submission_records(subject, grade, hw_name)
294
  rows = []
295
  for s in subs:
296
- needs_attention = s.get("total_score",0) < (min_attention if min_attention else s.get("total_questions",0)*0.6)
297
  rows.append([
298
  s.get("created_at",""),
299
  s.get("student_name",""),
300
  f"{s.get('total_score',0)}/{s.get('total_questions',0)}",
301
- "YES" if needs_attention else "NO",
302
  json.dumps({"per_item": s.get("per_item", []), "answers": s.get("answers", [])}, ensure_ascii=False)
303
  ])
304
  return rows, subs
305
 
306
- gen_btn.click(on_generate, inputs=[name_in, email_in, subject_in, grade_in, homework_name_in, complexity_in, brief_in, question_count], outputs=generated_out)
307
  ak_btn.click(on_generate_answer_key, inputs=[generated_out, subject_in, grade_in], outputs=answer_key_out)
308
  ak_save_btn.click(on_save_homework, inputs=[name_in, email_in, subject_in, grade_in, homework_name_in, complexity_in, brief_in, generated_out, answer_key_out], outputs=status)
309
 
310
  review_subject.change(load_review_homework_names, inputs=[review_subject, review_grade], outputs=review_hw_name)
311
  review_grade.change(load_review_homework_names, inputs=[review_subject, review_grade], outputs=review_hw_name)
312
- review_hw_name.change(build_submissions_table, inputs=[review_subject, review_grade, review_hw_name, min_attention_input], outputs=[submissions_table, submission_json])
313
- refresh_sub_btn.click(build_submissions_table, inputs=[review_subject, review_grade, review_hw_name, min_attention_input], outputs=[submissions_table, submission_json])
314
 
 
 
 
315
  with gr.TabItem("Student"):
316
  with gr.Row():
317
  with gr.Column(scale=1):
@@ -325,3 +318,85 @@ with gr.Blocks() as demo:
325
  answers_box = gr.Textbox(label="Your Answers (one per line)", lines=15, interactive=True)
326
  submit_btn = gr.Button("Submit Answers")
327
  result_out = gr.Textbox(label="Result", lines=4, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  # ----------------------------
53
 
54
  def read_remote_records() -> List[Dict[str, Any]]:
55
+ """Return ALL records (homework + submissions) from the remote jsonl file."""
56
  try:
57
  local_path = hf_hub_download(repo_id=REPO_ID, filename=FILE_NAME, repo_type=REPO_TYPE, token=HF_WRITE_TOKEN)
58
  with open(local_path, "r", encoding="utf-8") as f:
 
124
 
125
 
126
  def generate_answer_key(questions_text: str, subject: str, grade: str) -> str:
127
+ """Generate a concise answer key aligned to the provided numbered questions text."""
128
  prompt = (
129
  "You are an expert K-12 teacher creating an answer key.\n"
130
  "Given the following homework questions (a numbered list), produce a matching answer key as a numbered list, "
 
139
  # ----------------------------
140
 
141
  def grade_with_llm(questions: List[str], answers: List[str], answer_key_text: str, min_attention: int) -> Tuple[str, bool, List[Dict[str, Any]]]:
142
+ """Use the LLM to grade each answer 0/1 and provide brief feedback. Returns (summary_text, needs_attention, per_item)."""
143
  qa_pairs = []
144
  for i, q in enumerate(questions, start=1):
145
  a = answers[i-1] if i-1 < len(answers) else ""
 
150
  "Return STRICT JSON with this schema: {\n"
151
  " \"items\": [ { \"i\": number, \"score\": 0|1, \"feedback\": string } ... ],\n"
152
  " \"total\": number, \"out_of\": number, \"needs_attention\": boolean\n}\n\n"
 
153
  f"Answer Key:\n{answer_key_text}\n\n"
154
+ f"Questions + Student Answers:\n{json.dumps(qa_pairs, ensure_ascii=False)}\n\n"
155
  "Now output ONLY the JSON object, no extra commentary."
156
  )
157
 
 
163
  data = json.loads(blob)
164
  total = int(data.get("total", 0))
165
  out_of = int(data.get("out_of", len(questions)))
166
+ needs_attention = bool(data.get("needs_attention", total < min_attention))
167
  items = data.get("items", [])
168
  except Exception:
169
  total = sum(1 for a in answers if a.strip())
170
  out_of = len(questions)
171
+ needs_attention = total < min_attention
172
  items = [{"i": i+1, "score": 1 if (i < len(answers) and answers[i].strip()) else 0, "feedback": ""} for i in range(out_of)]
173
 
174
  summary = f"Score: {total}/{out_of}."
175
  return summary, needs_attention, items
176
 
177
  # ----------------------------
178
+ # Filtering helpers used by UI
179
  # ----------------------------
180
 
181
  def filter_homework_names(subject: str, grade: str) -> List[str]:
182
  records = read_remote_records()
183
  filtered = [r for r in records if r.get("record_type") == "homework" and r.get("subject") == subject and r.get("grade") == grade]
184
  names = [r.get("homework_name", "Unnamed Homework") for r in filtered]
185
+ names = list(dict.fromkeys(names)) # de-dup, keep order
186
  return names
187
 
 
188
  def get_homework_records(subject: str, grade: str, homework_name: str) -> List[Dict[str, Any]]:
189
  records = read_remote_records()
190
  matches = [r for r in records if r.get("record_type") == "homework" and r.get("subject") == subject and r.get("grade") == grade and r.get("homework_name") == homework_name]
191
  return matches
192
 
 
193
  def get_submission_records(subject: str, grade: str, homework_name: str) -> List[Dict[str, Any]]:
194
  records = read_remote_records()
195
  matches = [r for r in records if r.get("record_type") == "submission" and r.get("subject") == subject and r.get("grade") == grade and r.get("homework_name") == homework_name]
 
208
  min_attention_state = gr.State(0)
209
 
210
  with gr.Tabs():
211
+ # ----------------------------
212
+ # Teacher tab
213
+ # ----------------------------
214
  with gr.TabItem("Teacher"):
215
  with gr.Row():
216
  with gr.Column(scale=1):
 
221
  homework_name_in = gr.Textbox(label="Homework Name (e.g., Homework 1)")
222
  complexity_in = gr.Dropdown(label="Complexity", choices=["Easy", "Medium", "Hard"], value="Medium")
223
  brief_in = gr.Textbox(label="Homework Brief (describe topic & grade)", lines=4)
224
+ num_questions_in = gr.Dropdown(
 
225
  label="Number of Questions",
226
+ choices=[str(i) for i in range(1, 11)], # only 1-10 selectable
227
+ value="10"
 
228
  )
229
+ gr.Markdown("ℹ️ Pro-only: 11–50 questions available in premium version (disabled here).")
 
230
  gen_btn = gr.Button("Generate Homework", variant="primary")
231
 
232
  with gr.Column(scale=1):
 
238
  status = gr.Textbox(label="Status / Logs", interactive=False)
239
 
240
  gr.Markdown("### Review Submissions")
 
 
241
  with gr.Row():
242
  with gr.Column(scale=1):
243
+ min_attention_in = gr.Number(label="Set Minimum Attention Marks", value=0, interactive=True)
244
  review_subject = gr.Dropdown(label="Subject", choices=["Mathematics","Science","English","History","Geography","Other"], value="Mathematics")
245
  review_grade = gr.Dropdown(label="Grade", choices=[f"Grade {i}" for i in range(1,13)], value="Grade 5")
246
  review_hw_name = gr.Dropdown(label="Select Homework", choices=[], value=None, interactive=True)
 
249
  submissions_table = gr.Dataframe(headers=["Timestamp","Student","Score","Needs Attention","Details"], row_count=0, col_count=5, wrap=True)
250
  submission_json = gr.JSON(label="Selected Homework: Raw Submissions JSON", visible=False)
251
 
252
+ # Functions
253
+ def on_generate(subject, brief, num_q, complexity):
254
+ return generate_homework(subject, brief, num_questions=int(num_q), complexity=complexity)
 
 
255
 
256
  def on_generate_answer_key(questions_text, subject, grade):
 
 
257
  return generate_answer_key(questions_text, subject, grade)
258
 
259
  def on_save_homework(name, email, subject, grade, hw_name, complexity, brief, questions_text, answer_key_text):
 
 
260
  rec = {
261
  "record_type": "homework",
262
  "id": str(uuid.uuid4()),
 
281
  return gr.update(choices=names, interactive=True, value=names[0])
282
 
283
  def build_submissions_table(subject, grade, hw_name, min_attention):
284
+ subs = get_submission_records(subject, grade, hw_name) if hw_name else []
 
 
285
  rows = []
286
  for s in subs:
 
287
  rows.append([
288
  s.get("created_at",""),
289
  s.get("student_name",""),
290
  f"{s.get('total_score',0)}/{s.get('total_questions',0)}",
291
+ "YES" if s.get("total_score",0) < min_attention else "NO",
292
  json.dumps({"per_item": s.get("per_item", []), "answers": s.get("answers", [])}, ensure_ascii=False)
293
  ])
294
  return rows, subs
295
 
296
+ gen_btn.click(on_generate, inputs=[subject_in, brief_in, num_questions_in, complexity_in], outputs=generated_out)
297
  ak_btn.click(on_generate_answer_key, inputs=[generated_out, subject_in, grade_in], outputs=answer_key_out)
298
  ak_save_btn.click(on_save_homework, inputs=[name_in, email_in, subject_in, grade_in, homework_name_in, complexity_in, brief_in, generated_out, answer_key_out], outputs=status)
299
 
300
  review_subject.change(load_review_homework_names, inputs=[review_subject, review_grade], outputs=review_hw_name)
301
  review_grade.change(load_review_homework_names, inputs=[review_subject, review_grade], outputs=review_hw_name)
302
+ review_hw_name.change(build_submissions_table, inputs=[review_subject, review_grade, review_hw_name, min_attention_in], outputs=[submissions_table, submission_json])
303
+ refresh_sub_btn.click(build_submissions_table, inputs=[review_subject, review_grade, review_hw_name, min_attention_in], outputs=[submissions_table, submission_json])
304
 
305
+ # ----------------------------
306
+ # Student tab
307
+ # ----------------------------
308
  with gr.TabItem("Student"):
309
  with gr.Row():
310
  with gr.Column(scale=1):
 
318
  answers_box = gr.Textbox(label="Your Answers (one per line)", lines=15, interactive=True)
319
  submit_btn = gr.Button("Submit Answers")
320
  result_out = gr.Textbox(label="Result", lines=4, interactive=False)
321
+
322
+ def load_homework_names(subject, grade):
323
+ names = filter_homework_names(subject, grade)
324
+ if not names:
325
+ return gr.update(choices=[], interactive=False, value=None), "", [], None, ""
326
+ default_name = names[0]
327
+ matches = get_homework_records(subject, grade, default_name)
328
+ questions_text = "\n\n".join(m.get("final_questions", "") for m in matches if m.get("final_questions"))
329
+ questions = parse_questions(questions_text)
330
+ answer_key_text = ""
331
+ if matches:
332
+ matches.sort(key=lambda r: r.get("created_at",""), reverse=True)
333
+ for m in matches:
334
+ if m.get("answer_key"):
335
+ answer_key_text = m.get("answer_key")
336
+ break
337
+ start = time.time()
338
+ return gr.update(choices=names, interactive=True, value=default_name), questions_text, questions, start, answer_key_text
339
+
340
+ def load_questions_by_name(hw_name, subject, grade):
341
+ if hw_name is None:
342
+ return "", [], None, ""
343
+ matches = get_homework_records(subject, grade, hw_name)
344
+ if not matches:
345
+ return "", [], None, ""
346
+ questions_text = "\n\n".join(m.get("final_questions", "") for m in matches if m.get("final_questions"))
347
+ questions = parse_questions(questions_text)
348
+ answer_key_text = ""
349
+ matches.sort(key=lambda r: r.get("created_at",""), reverse=True)
350
+ for m in matches:
351
+ if m.get("answer_key"):
352
+ answer_key_text = m.get("answer_key")
353
+ break
354
+ start = time.time()
355
+ return questions_text, questions, start, answer_key_text
356
+
357
+ def submit_answers(questions, answers, start, student_name_val, student_grade_val, subject_val, hw_name_val, answer_key_text, min_attention):
358
+ if start is None:
359
+ start = time.time()
360
+ time_taken = time.time() - start
361
+ ans_list = [a.strip() for a in answers.splitlines()]
362
+ summary, needs_attention, per_item = grade_with_llm(questions, ans_list, answer_key_text, min_attention)
363
+ rec = {
364
+ "record_type": "submission",
365
+ "id": str(uuid.uuid4()),
366
+ "student_name": student_name_val,
367
+ "student_grade": student_grade_val,
368
+ "student_subject": subject_val,
369
+ "subject": subject_val,
370
+ "grade": student_grade_val,
371
+ "homework_name": hw_name_val,
372
+ "answers": ans_list,
373
+ "total_score": int(summary.split(":")[1].split("/")[0]),
374
+ "total_questions": len(questions),
375
+ "per_item": per_item,
376
+ "created_at": datetime.now().isoformat(),
377
+ }
378
+ append_and_push_record(rec)
379
+ return summary
380
+
381
+ student_subject.change(load_homework_names, inputs=[student_subject, student_grade], outputs=[homework_name_dd, questions_box, current_questions, start_time, answer_key_state])
382
+ student_grade.change(load_homework_names, inputs=[student_subject, student_grade], outputs=[homework_name_dd, questions_box, current_questions, start_time, answer_key_state])
383
+ homework_name_dd.change(load_questions_by_name, inputs=[homework_name_dd, student_subject, student_grade], outputs=[questions_box, current_questions, start_time, answer_key_state])
384
+ submit_btn.click(submit_answers, inputs=[current_questions, answers_box, start_time, student_name, student_grade, student_subject, homework_name_dd, answer_key_state, min_attention_state], outputs=result_out)
385
+
386
+ # ----------------------------
387
+ # Rough Work tab
388
+ # ----------------------------
389
+ with gr.TabItem("Rough Work"):
390
+ rough_input = gr.Textbox(label="Enter your questions or doubts here", lines=10, interactive=True)
391
+ get_hint_btn = gr.Button("Get Hint")
392
+ hint_output = gr.Textbox(label="AI-generated Hint", lines=5, interactive=False)
393
+
394
+ def generate_hint(text):
395
+ if not text.strip():
396
+ return "Please enter some text for hints."
397
+ return call_groq_api(f"You are a helpful tutor. Give hints based on this: {text}", temperature=0.7, max_tokens=120)
398
+
399
+ get_hint_btn.click(generate_hint, inputs=rough_input, outputs=hint_output)
400
+
401
+ if __name__ == "__main__":
402
+ demo.launch()