Spaces:
Sleeping
Sleeping
capradeepgujaran
commited on
Commit
•
4be5ff1
1
Parent(s):
65b80b0
Update app.py
Browse files
app.py
CHANGED
@@ -16,16 +16,10 @@ class QuizApp:
|
|
16 |
self.current_questions = []
|
17 |
|
18 |
def generate_questions(self, text, num_questions):
|
19 |
-
prompt = f"""Create {num_questions} multiple choice questions based on this text:
|
20 |
{text}
|
21 |
|
22 |
-
|
23 |
-
1. Have a clear, concise question text
|
24 |
-
2. Have exactly 4 options
|
25 |
-
3. Have only one correct answer
|
26 |
-
4. Be educational and test understanding
|
27 |
-
|
28 |
-
Return in this exact JSON format:
|
29 |
[
|
30 |
{{
|
31 |
"question": "What is the main topic discussed?",
|
@@ -36,26 +30,92 @@ class QuizApp:
|
|
36 |
"Wrong answer 3"
|
37 |
],
|
38 |
"correct_answer": 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
}}
|
40 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
try:
|
43 |
response = client.chat.completions.create(
|
44 |
messages=[
|
45 |
-
{
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
],
|
48 |
model="llama-3.2-3b-preview",
|
49 |
temperature=0.5,
|
50 |
max_tokens=2048
|
51 |
)
|
52 |
|
|
|
53 |
response_text = response.choices[0].message.content.strip()
|
|
|
54 |
response_text = response_text.replace("```json", "").replace("```", "").strip()
|
55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
questions = json.loads(response_text)
|
57 |
-
|
58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
except Exception as e:
|
61 |
print(f"Error generating questions: {e}")
|
@@ -135,19 +195,28 @@ def create_quiz_interface():
|
|
135 |
value="Professional Assessment Certification"
|
136 |
)
|
137 |
certificate_display = gr.Image(label="Your Certificate")
|
138 |
-
|
|
|
139 |
def update_questions(text, num_questions):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
success, questions = quiz_app.generate_questions(text, num_questions)
|
141 |
-
if not success:
|
142 |
return (
|
143 |
-
gr.update(value="Failed to generate questions. Please try again."),
|
144 |
*[gr.update(visible=False, choices=[]) for _ in range(5)],
|
145 |
-
|
146 |
0
|
147 |
)
|
148 |
|
149 |
# Update question display
|
150 |
-
questions_html = ""
|
151 |
for i, q in enumerate(questions, 1):
|
152 |
questions_html += f"### Question {i}\n{q['question']}\n\n"
|
153 |
|
@@ -158,13 +227,15 @@ def create_quiz_interface():
|
|
158 |
updates.append(gr.update(
|
159 |
visible=True,
|
160 |
choices=questions[i]["options"],
|
161 |
-
value=None
|
|
|
162 |
))
|
163 |
else:
|
164 |
updates.append(gr.update(visible=False, choices=[]))
|
165 |
|
166 |
return (gr.update(value=questions_html), *updates, questions, 1)
|
167 |
|
|
|
168 |
def submit_quiz(q1, q2, q3, q4, q5, questions):
|
169 |
answers = [q1, q2, q3, q4, q5][:len(questions)]
|
170 |
score = quiz_app.calculate_score(answers)
|
|
|
16 |
self.current_questions = []
|
17 |
|
18 |
def generate_questions(self, text, num_questions):
|
19 |
+
prompt = f"""Create exactly {num_questions} multiple choice questions based on this text:
|
20 |
{text}
|
21 |
|
22 |
+
Format your response EXACTLY like this example:
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
[
|
24 |
{{
|
25 |
"question": "What is the main topic discussed?",
|
|
|
30 |
"Wrong answer 3"
|
31 |
],
|
32 |
"correct_answer": 0
|
33 |
+
}},
|
34 |
+
{{
|
35 |
+
"question": "Another question here?",
|
36 |
+
"options": [
|
37 |
+
"Correct answer",
|
38 |
+
"Wrong answer 1",
|
39 |
+
"Wrong answer 2",
|
40 |
+
"Wrong answer 3"
|
41 |
+
],
|
42 |
+
"correct_answer": 0
|
43 |
}}
|
44 |
+
]
|
45 |
+
|
46 |
+
Important:
|
47 |
+
- Return ONLY the JSON array
|
48 |
+
- Each question must have exactly 4 options
|
49 |
+
- correct_answer must be the index (0-3) of the correct option
|
50 |
+
- Do not add any explanation or additional text
|
51 |
+
"""
|
52 |
|
53 |
try:
|
54 |
response = client.chat.completions.create(
|
55 |
messages=[
|
56 |
+
{
|
57 |
+
"role": "system",
|
58 |
+
"content": "You are a quiz generator that creates clear, single-choice questions. Always respond with valid JSON array only."
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"role": "user",
|
62 |
+
"content": prompt
|
63 |
+
}
|
64 |
],
|
65 |
model="llama-3.2-3b-preview",
|
66 |
temperature=0.5,
|
67 |
max_tokens=2048
|
68 |
)
|
69 |
|
70 |
+
# Clean up the response
|
71 |
response_text = response.choices[0].message.content.strip()
|
72 |
+
# Remove any markdown formatting or additional text
|
73 |
response_text = response_text.replace("```json", "").replace("```", "").strip()
|
74 |
|
75 |
+
# Ensure response starts with [ and ends with ]
|
76 |
+
response_text = response_text[response_text.find("["):response_text.rfind("]")+1]
|
77 |
+
|
78 |
+
print("Generated response:", response_text) # Debug print
|
79 |
+
|
80 |
+
# Parse and validate questions
|
81 |
questions = json.loads(response_text)
|
82 |
+
if not isinstance(questions, list):
|
83 |
+
raise ValueError("Response is not a list")
|
84 |
+
|
85 |
+
# Validate each question
|
86 |
+
validated_questions = []
|
87 |
+
for q in questions:
|
88 |
+
if not isinstance(q, dict):
|
89 |
+
continue
|
90 |
+
if not all(key in q for key in ["question", "options", "correct_answer"]):
|
91 |
+
continue
|
92 |
+
if not isinstance(q["options"], list) or len(q["options"]) != 4:
|
93 |
+
continue
|
94 |
+
if not isinstance(q["correct_answer"], int) or q["correct_answer"] not in range(4):
|
95 |
+
continue
|
96 |
+
validated_questions.append(q)
|
97 |
+
|
98 |
+
if not validated_questions:
|
99 |
+
raise ValueError("No valid questions generated")
|
100 |
+
|
101 |
+
self.current_questions = validated_questions
|
102 |
+
return True, validated_questions
|
103 |
+
|
104 |
+
except json.JSONDecodeError as e:
|
105 |
+
print(f"JSON parsing error: {e}")
|
106 |
+
# Return a default question for testing/debugging
|
107 |
+
default_questions = [{
|
108 |
+
"question": "Sample question (Error occurred in generation)",
|
109 |
+
"options": [
|
110 |
+
"Option 1",
|
111 |
+
"Option 2",
|
112 |
+
"Option 3",
|
113 |
+
"Option 4"
|
114 |
+
],
|
115 |
+
"correct_answer": 0
|
116 |
+
}]
|
117 |
+
self.current_questions = default_questions
|
118 |
+
return True, default_questions
|
119 |
|
120 |
except Exception as e:
|
121 |
print(f"Error generating questions: {e}")
|
|
|
195 |
value="Professional Assessment Certification"
|
196 |
)
|
197 |
certificate_display = gr.Image(label="Your Certificate")
|
198 |
+
|
199 |
+
|
200 |
def update_questions(text, num_questions):
|
201 |
+
if not text.strip():
|
202 |
+
return (
|
203 |
+
gr.update(value="Please enter some text content to generate questions."),
|
204 |
+
*[gr.update(visible=False, choices=[]) for _ in range(5)],
|
205 |
+
[],
|
206 |
+
0
|
207 |
+
)
|
208 |
+
|
209 |
success, questions = quiz_app.generate_questions(text, num_questions)
|
210 |
+
if not success or not questions:
|
211 |
return (
|
212 |
+
gr.update(value="Failed to generate questions. Please try again with different content."),
|
213 |
*[gr.update(visible=False, choices=[]) for _ in range(5)],
|
214 |
+
[],
|
215 |
0
|
216 |
)
|
217 |
|
218 |
# Update question display
|
219 |
+
questions_html = "### Answer all questions below:\n\n"
|
220 |
for i, q in enumerate(questions, 1):
|
221 |
questions_html += f"### Question {i}\n{q['question']}\n\n"
|
222 |
|
|
|
227 |
updates.append(gr.update(
|
228 |
visible=True,
|
229 |
choices=questions[i]["options"],
|
230 |
+
value=None,
|
231 |
+
label=f"Question {i+1}"
|
232 |
))
|
233 |
else:
|
234 |
updates.append(gr.update(visible=False, choices=[]))
|
235 |
|
236 |
return (gr.update(value=questions_html), *updates, questions, 1)
|
237 |
|
238 |
+
|
239 |
def submit_quiz(q1, q2, q3, q4, q5, questions):
|
240 |
answers = [q1, q2, q3, q4, q5][:len(questions)]
|
241 |
score = quiz_app.calculate_score(answers)
|