muhammadrazapathan commited on
Commit
b916139
Β·
verified Β·
1 Parent(s): 8d20b5f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -75
app.py CHANGED
@@ -1,71 +1,211 @@
 
 
 
 
 
 
1
  # ============================
2
- # MODERN GRADIO UI
3
  # ============================
 
4
 
5
- custom_css = """
6
- body {
7
- background: linear-gradient(135deg, #0f172a, #1e293b);
8
- }
9
- .gradio-container {
10
- max-width: 900px !important;
11
- margin: auto;
12
- }
13
- h1, h2, h3 {
14
- text-align: center;
15
- }
16
- """
17
 
18
- with gr.Blocks(title="Smart Quiz Generator", css=custom_css, theme=gr.themes.Soft()) as app:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- gr.Markdown("""
21
- # 🧠 Smart Quiz Generator
22
- ### AI-Powered Unlimited MCQ System
23
- Turn your study material into interactive quizzes instantly.
24
- """)
 
 
 
 
 
25
 
26
- with gr.Tabs():
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- # ================= QUIZ TAB =================
29
- with gr.Tab("πŸ“ Take Quiz"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- with gr.Group():
32
- text_input = gr.Textbox(
33
- lines=6,
34
- label="πŸ“š Paste Study Material",
35
- placeholder="Paste your notes or study content here..."
36
- )
37
 
38
- pdf_input = gr.File(
39
- file_types=[".pdf"],
40
- file_count="multiple",
41
- label="πŸ“‚ Upload PDF Books"
42
- )
43
 
44
- pdf_selector = gr.Dropdown(
45
- label="πŸ“– Select Uploaded Book",
46
- choices=[]
47
- )
 
 
48
 
49
- with gr.Row():
50
- num_questions = gr.Number(
51
- label="❓ Number of Questions",
52
- value=10,
53
- precision=0
54
- )
55
 
56
- timer_minutes = gr.Number(
57
- label="⏱ Duration (Minutes)",
58
- value=10
59
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- start_btn = gr.Button("πŸš€ Start Quiz", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- gr.Markdown("---")
 
 
 
 
 
 
 
 
 
64
 
65
- question_box = gr.Markdown()
66
- options_radio = gr.Radio(label="Choose Your Answer")
67
- submit_btn = gr.Button("βœ… Submit Answer", variant="secondary")
 
 
 
 
 
 
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  score_display = gr.Markdown()
70
  timer_display = gr.Markdown()
71
 
@@ -75,43 +215,26 @@ with gr.Blocks(title="Smart Quiz Generator", css=custom_css, theme=gr.themes.Sof
75
  endtime_state = gr.State()
76
  pdf_library_state = gr.State({})
77
 
78
- # ================= DASHBOARD TAB =================
79
- with gr.Tab("πŸ“Š Performance Dashboard"):
80
-
81
- dash_btn = gr.Button("πŸ”„ Refresh Dashboard", variant="primary")
82
-
83
  dash_summary = gr.Markdown()
84
  dash_table = gr.Dataframe()
85
-
86
- download_btn = gr.Button("⬇ Download Results")
87
  download_file = gr.File()
88
 
89
- # ================= FOOTER =================
90
- gr.Markdown("""
91
- ---
92
- πŸ”₯ Built by Muhammad Raza | Generative AI Engineer
93
- Transforming Education with AI
94
- """)
95
-
96
  # ---------------- EVENTS ----------------
97
- pdf_input.change(
98
- load_multiple_pdfs,
99
- inputs=pdf_input,
100
- outputs=[pdf_library_state, pdf_selector]
101
- )
102
 
103
  start_btn.click(
104
  prepare_quiz,
105
  inputs=[text_input, pdf_library_state, pdf_selector, num_questions, timer_minutes],
106
- outputs=[question_box, options_radio, score_display,
107
- quiz_state, index_state, score_state, endtime_state, timer_display]
108
  )
109
 
110
  submit_btn.click(
111
  submit_answer,
112
  inputs=[options_radio, quiz_state, index_state, score_state, endtime_state],
113
- outputs=[question_box, options_radio, score_display,
114
- quiz_state, index_state, score_state, endtime_state, timer_display]
115
  )
116
 
117
  dash_btn.click(get_dashboard, outputs=[dash_summary, dash_table])
 
1
+ import gradio as gr
2
+ import random
3
+ import time
4
+ import pandas as pd
5
+ from PyPDF2 import PdfReader
6
+
7
  # ============================
8
+ # GLOBALS
9
  # ============================
10
+ quiz_history = []
11
 
12
+ # ============================
13
+ # Extract sentences
14
+ # ============================
15
+ def extract_sentences(text):
16
+ sentences = [s.strip() for s in text.split(".") if len(s.strip()) > 20]
17
+ return sentences
 
 
 
 
 
 
18
 
19
+ # ============================
20
+ # Generate quiz
21
+ # ============================
22
+ def generate_quiz(text, num_questions):
23
+ try:
24
+ num_questions = int(num_questions)
25
+ if num_questions <= 0:
26
+ num_questions = 10
27
+ except:
28
+ num_questions = 10
29
+
30
+ sentences = extract_sentences(text)
31
+ if len(sentences) == 0:
32
+ return [], "❌ Not enough content to generate quiz."
33
+
34
+ selected = [random.choice(sentences) for _ in range(num_questions)]
35
+ quiz = []
36
+
37
+ for s in selected:
38
+ words = s.split()
39
+ if len(words) < 6:
40
+ continue
41
+ answer = random.choice(words)
42
+ question = s.replace(answer, "_____")
43
+ options = list(set(words))
44
+ random.shuffle(options)
45
+ options = options[:3]
46
+ options.append(answer)
47
+ random.shuffle(options)
48
+ quiz.append({
49
+ "question": question,
50
+ "options": options,
51
+ "answer": answer
52
+ })
53
+
54
+ return quiz, f"βœ… Generated {len(quiz)} questions successfully!"
55
 
56
+ # ============================
57
+ # Display quiz
58
+ # ============================
59
+ def show_quiz(quiz):
60
+ output = ""
61
+ for i, q in enumerate(quiz):
62
+ output += f"\nQ{i+1}. {q['question']}\n"
63
+ for opt in q["options"]:
64
+ output += f" β€’ {opt}\n"
65
+ return output
66
 
67
+ # ============================
68
+ # Submit answer
69
+ # ============================
70
+ def submit_answer(selected, quiz, index, score, end_time):
71
+ if quiz is None or len(quiz) == 0:
72
+ return "❌ Generate quiz first!", None, None, None, None, None, None, ""
73
+ if index >= len(quiz):
74
+ return "βœ… Quiz Finished!", None, None, None, None, None, None, ""
75
+ if selected == quiz[index]["answer"]:
76
+ score += 1
77
+ index += 1
78
+ return show_question(quiz, index, score, end_time)
79
 
80
+ # ============================
81
+ # Show question
82
+ # ============================
83
+ def show_question(quiz, index, score, end_time):
84
+ if quiz is None or len(quiz) == 0:
85
+ return "❌ No quiz found.", None, None, None, None, None, None, ""
86
+ if index >= len(quiz) or time.time() > end_time:
87
+ percent = (score / len(quiz)) * 100
88
+ quiz_history.append({
89
+ "Score": score,
90
+ "Total": len(quiz),
91
+ "Percentage": round(percent, 2),
92
+ "Time": time.strftime("%H:%M:%S")
93
+ })
94
+ return (f"βœ… Quiz Finished! Score: {score}/{len(quiz)} ({percent:.1f}%)",
95
+ None, None, None, None, None, None, "")
96
+ q = quiz[index]
97
+ remaining = int(end_time - time.time())
98
+ return (
99
+ f"### Question {index+1}:\n\n{q['question']}",
100
+ gr.update(choices=q["options"], value=None),
101
+ f"Score: {score}",
102
+ quiz,
103
+ index,
104
+ score,
105
+ end_time,
106
+ f"⏳ Time Left: {remaining} seconds"
107
+ )
108
 
109
+ # ============================
110
+ # Prepare quiz (text or PDF)
111
+ # ============================
112
+ def prepare_quiz(text, pdf_library, selected_pdf, num_questions, timer_minutes):
113
+ if selected_pdf and selected_pdf in pdf_library:
114
+ text = pdf_library[selected_pdf]
115
 
116
+ if not text or text.strip() == "":
117
+ return "⚠️ Provide text or select a PDF.", None, None, None, None, None, None, ""
 
 
 
118
 
119
+ try:
120
+ timer_minutes = float(timer_minutes)
121
+ if timer_minutes <= 0:
122
+ timer_minutes = 10
123
+ except:
124
+ timer_minutes = 10
125
 
126
+ quiz, msg = generate_quiz(text, num_questions)
127
+ end_time = time.time() + timer_minutes*60
128
+ return show_question(quiz, 0, 0, end_time)
 
 
 
129
 
130
+ # ============================
131
+ # Load multiple PDFs
132
+ # ============================
133
+ def load_multiple_pdfs(files):
134
+ if files is None:
135
+ return {}, gr.update(choices=[])
136
+
137
+ pdf_texts = {}
138
+ names = []
139
+
140
+ for file in files:
141
+ try:
142
+ text = ""
143
+ with open(file.name, "rb") as f:
144
+ pdf = PdfReader(f)
145
+ for page in pdf.pages:
146
+ page_text = page.extract_text()
147
+ if page_text:
148
+ text += page_text + " "
149
+ name = file.name.split("/")[-1]
150
+ pdf_texts[name] = text.strip()
151
+ names.append(name)
152
+ except Exception as e:
153
+ print("PDF Error:", e)
154
+
155
+ return pdf_texts, gr.update(choices=names, value=names[0] if names else None)
156
 
157
+ # ============================
158
+ # Dashboard summary
159
+ # ============================
160
+ def get_dashboard():
161
+ if not quiz_history:
162
+ return "No attempts yet.", None
163
+ df = pd.DataFrame(quiz_history)
164
+ summary = f"""
165
+ ### πŸ“Š Performance Summary
166
+ Attempts: {len(df)}
167
+ Best Score: {df['Percentage'].max():.1f}%
168
+ Average Score: {df['Percentage'].mean():.1f}%
169
+ """
170
+ return summary, df
171
 
172
+ # ============================
173
+ # Save CSV
174
+ # ============================
175
+ def save_results():
176
+ if not quiz_history:
177
+ return None
178
+ df = pd.DataFrame(quiz_history)
179
+ file = "quiz_results.csv"
180
+ df.to_csv(file, index=False)
181
+ return file
182
 
183
+ # ============================
184
+ # GRADIO UI
185
+ # ============================
186
+ with gr.Blocks(title="Smart Quiz Generator") as app:
187
+
188
+ gr.Markdown("# 🧠 Smart Quiz Generator")
189
+
190
+ with gr.Tabs():
191
+ with gr.Tab("πŸ“ Take Quiz"):
192
 
193
+ text_input = gr.Textbox(lines=6, label="Paste Study Material")
194
+
195
+ pdf_input = gr.File(file_types=[".pdf"], file_count="multiple", label="Upload PDFs")
196
+ pdf_selector = gr.Dropdown(label="Select Book", choices=[])
197
+
198
+ with gr.Tabs():
199
+ with gr.Tab("❓ Select Objectives"):
200
+ num_questions = gr.Number(label="Number of Questions (No Limit)", value=10, precision=0)
201
+ with gr.Tab("⏱ Select Time"):
202
+ timer_minutes = gr.Number(label="Quiz Duration in Minutes (No Limit)", value=10)
203
+
204
+ start_btn = gr.Button("Start Quiz")
205
+
206
+ question_box = gr.Markdown()
207
+ options_radio = gr.Radio(label="Choose Answer")
208
+ submit_btn = gr.Button("Submit Answer")
209
  score_display = gr.Markdown()
210
  timer_display = gr.Markdown()
211
 
 
215
  endtime_state = gr.State()
216
  pdf_library_state = gr.State({})
217
 
218
+ with gr.Tab("πŸ“Š Dashboard"):
219
+ dash_btn = gr.Button("Refresh Dashboard")
 
 
 
220
  dash_summary = gr.Markdown()
221
  dash_table = gr.Dataframe()
222
+ download_btn = gr.Button("Download Results")
 
223
  download_file = gr.File()
224
 
 
 
 
 
 
 
 
225
  # ---------------- EVENTS ----------------
226
+ pdf_input.change(load_multiple_pdfs, inputs=pdf_input, outputs=[pdf_library_state, pdf_selector])
 
 
 
 
227
 
228
  start_btn.click(
229
  prepare_quiz,
230
  inputs=[text_input, pdf_library_state, pdf_selector, num_questions, timer_minutes],
231
+ outputs=[question_box, options_radio, score_display, quiz_state, index_state, score_state, endtime_state, timer_display]
 
232
  )
233
 
234
  submit_btn.click(
235
  submit_answer,
236
  inputs=[options_radio, quiz_state, index_state, score_state, endtime_state],
237
+ outputs=[question_box, options_radio, score_display, quiz_state, index_state, score_state, endtime_state, timer_display]
 
238
  )
239
 
240
  dash_btn.click(get_dashboard, outputs=[dash_summary, dash_table])