Benny-Tang commited on
Commit
722325d
·
verified ·
1 Parent(s): bb476e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -107
app.py CHANGED
@@ -1,130 +1,83 @@
1
  import os
2
  import random
3
  import gradio as gr
4
- from demo_questions import QUESTIONS # demo 60 questions
5
 
 
 
 
6
 
7
- # =====================================================
8
- # Load Exam
9
- # =====================================================
10
  def load_exam(subject):
11
- """Load 10 random questions for a subject (from demo_questions)."""
12
- try:
13
- if subject in QUESTIONS:
14
- qlist = random.sample(QUESTIONS[subject], min(10, len(QUESTIONS[subject])))
15
- else:
16
- qlist = []
17
- except Exception as e:
18
- print(f"⚠️ Error loading questions for {subject}: {e}")
19
- qlist = []
20
-
21
- outputs = []
22
-
23
- # Generate 10 question slots
24
- for i in range(10):
25
- if i < len(qlist):
26
- q = qlist[i]
27
- outputs.append({"value": f"**Q{i+1}:** {q['text']}"}) # for Markdown
28
- outputs.append({"choices": q['choices'], "value": None}) # for Radio
29
- else:
30
- outputs.append({"value": f"Q{i+1}: (No Question)"})
31
- outputs.append({"choices": [], "value": None})
32
-
33
- # Show submit button
34
- outputs.append({"visible": True})
35
-
36
- # Save state with selected questions
37
- outputs.append(qlist)
38
 
 
 
39
  return outputs
40
 
41
 
42
- # =====================================================
43
- # Submit Answers
44
- # =====================================================
45
- def submit_exam_answers(*args):
46
- """
47
- Args:
48
- First 20 are answers (from radios)
49
- Last one is the state (qlist with correct answers)
50
- """
51
- answers = args[:-1]
52
- qlist = args[-1]
53
-
54
- if not qlist:
55
- return "⚠️ No questions loaded.", "", "", ""
56
-
57
- score = 0
58
- results = []
59
- for i, q in enumerate(qlist):
60
- user_ans = answers[i]
61
- correct = q.get("answer", None)
62
- if user_ans == correct:
63
- score += 1
64
- results.append(f"✅ Q{i+1}: Correct")
65
- else:
66
- results.append(f"❌ Q{i+1}: Your answer: {user_ans}, Correct: {correct}")
67
-
68
- total = len(qlist)
69
- analysis = "\n".join(results)
70
- coach = f"Your Score: {score}/{total}\nKeep practicing to improve!"
71
-
72
- # Placeholder for predictive agent
73
- predictions = "📊 Predictive Agent: Future hot topics may include grammar, peribahasa, algebra, and world history."
74
-
75
- return f"✅ Final Score: {score}/{total}", analysis, coach, predictions
76
-
77
-
78
- # =====================================================
79
- # Build Gradio UI
80
- # =====================================================
81
- with gr.Blocks(title="SPM Exam Simulator (Form 5)") as demo:
82
- gr.Markdown("# 🎓 SPM Exam Simulator (Form 5)")
83
- gr.Markdown("Practice core subjects for upcoming SPM exam (2018–2024 past papers, AI-predicted questions, and OCR upload support).")
84
-
85
- with gr.Row():
86
- subject = gr.Dropdown(
87
- ["BM", "English", "Math", "History", "Science", "MoralStudies"],
88
- label="Choose Subject",
89
- value="BM"
90
- )
91
- load_btn = gr.Button("📘 Load Exam")
92
-
93
- # Question placeholders (10 questions × text + radio)
94
- q_markdowns = [gr.Markdown(f"Q{i+1}: (Not Loaded)") for i in range(10)]
95
- q_radios = [gr.Radio(choices=[], label=f"Answer Q{i+1}") for i in range(10)]
96
-
97
- # Submit
98
- submit_btn = gr.Button("✅ Submit Answers", visible=False)
99
-
100
- # Outputs
101
- score_out = gr.Markdown()
102
- analysis_out = gr.Markdown()
103
- coach_out = gr.Markdown()
104
- pred_out = gr.Markdown()
105
-
106
- # Hidden state for selected questions
107
- state = gr.State([])
108
-
109
- # Events
110
  load_btn.click(
111
  fn=load_exam,
112
- inputs=[subject],
113
- outputs=q_markdowns + q_radios + [submit_btn, state]
114
  )
115
 
116
  submit_btn.click(
117
  fn=submit_exam_answers,
118
- inputs=q_radios + [state],
119
- outputs=[score_out, analysis_out, coach_out, pred_out]
120
  )
121
 
122
-
123
- # =====================================================
124
  # Launch
125
- # =====================================================
 
126
  if __name__ == "__main__":
127
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
128
 
129
 
130
 
 
1
  import os
2
  import random
3
  import gradio as gr
4
+ from demo_questions import QUESTIONS # demo questions (60 across 6 subjects)
5
 
6
+ # -----------------------------
7
+ # Helper functions
8
+ # -----------------------------
9
 
 
 
 
10
  def load_exam(subject):
11
+ """Load 10 random questions from the selected subject."""
12
+ all_questions = QUESTIONS.get(subject, [])
13
+ if not all_questions:
14
+ return [f"**Q{i+1}:** (No Question)" for i in range(10)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ questions = random.sample(all_questions, min(10, len(all_questions)))
17
+ outputs = [f"**Q{i+1}:** {q}" for i, q in enumerate(questions)]
18
  return outputs
19
 
20
 
21
+ def submit_exam_answers(*answers):
22
+ """Process submitted answers. For now, just echo them back."""
23
+ submitted = [f"Q{i+1}: {ans}" for i, ans in enumerate(answers, 1)]
24
+ return "\n".join(submitted)
25
+
26
+
27
+ # -----------------------------
28
+ # Gradio UI
29
+ # -----------------------------
30
+
31
+ with gr.Blocks() as demo:
32
+ gr.Markdown("# 📘 SPM Exam Simulator")
33
+
34
+ subject = gr.Dropdown(
35
+ choices=list(QUESTIONS.keys()),
36
+ label="Select Subject",
37
+ value="BM"
38
+ )
39
+
40
+ load_btn = gr.Button("Load Exam")
41
+
42
+ question_boxes = []
43
+ answer_boxes = []
44
+
45
+ with gr.Column():
46
+ for i in range(10):
47
+ q_box = gr.Markdown(f"**Q{i+1}:** (empty)")
48
+ a_box = gr.Textbox(
49
+ label=f"Answer Q{i+1}",
50
+ lines=2,
51
+ placeholder="Type your answer here (e.g., A/B/C/D or essay)..."
52
+ )
53
+ question_boxes.append(q_box)
54
+ answer_boxes.append(a_box)
55
+
56
+ submit_btn = gr.Button("Submit Answers")
57
+ result = gr.Textbox(label="Submission Result", interactive=False, lines=15)
58
+
59
+ # -----------------------------
60
+ # Button bindings
61
+ # -----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  load_btn.click(
63
  fn=load_exam,
64
+ inputs=subject,
65
+ outputs=question_boxes
66
  )
67
 
68
  submit_btn.click(
69
  fn=submit_exam_answers,
70
+ inputs=answer_boxes,
71
+ outputs=result
72
  )
73
 
74
+ # -----------------------------
 
75
  # Launch
76
+ # -----------------------------
77
+
78
  if __name__ == "__main__":
79
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False, ssr_mode=True)
80
+
81
 
82
 
83