Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -10,79 +10,102 @@ GROQ_API_KEY = "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"
|
|
10 |
st.title('π― AI Quiz Generator')
|
11 |
st.subheader('π Test Your Knowledge!')
|
12 |
|
13 |
-
#
|
14 |
standard = st.text_input('π Enter Standard/Grade')
|
15 |
topic = st.text_input('π Enter Topic')
|
|
|
|
|
16 |
quiz_type = st.selectbox("π Select Quiz Type", ["Multiple Choice Questions (MCQ)", "True or False", "Fill in the Blanks"])
|
|
|
|
|
17 |
difficulty = st.radio("π Select Difficulty Level", ["Low", "Medium", "Hard"])
|
|
|
|
|
18 |
num_questions = st.slider("π’ Select Number of Questions", min_value=1, max_value=10, value=5)
|
19 |
|
20 |
# Initialize AI Model
|
21 |
model = ChatGroq(
|
22 |
temperature=0.6,
|
23 |
groq_api_key=GROQ_API_KEY,
|
24 |
-
model_name="llama-3.3-70b-versatile"
|
25 |
)
|
26 |
|
27 |
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
28 |
-
"""Generate quiz
|
29 |
-
|
30 |
if quiz_type == "Multiple Choice Questions (MCQ)":
|
31 |
prompt = f"""
|
32 |
Generate {num_questions} multiple choice questions (MCQs) for a {standard} student on {topic}.
|
33 |
Each question should have exactly 4 options (A, B, C, D) and one correct answer.
|
34 |
-
Return the result in
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
D) Option 4
|
41 |
-
|
42 |
-
Answer: Correct Option (A, B, C, or D)
|
43 |
"""
|
44 |
elif quiz_type == "True or False":
|
45 |
prompt = f"""
|
46 |
Generate {num_questions} True or False questions for a {standard} student on {topic}.
|
47 |
-
Return the result in
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
51 |
"""
|
52 |
else: # Fill in the Blanks
|
53 |
prompt = f"""
|
54 |
Generate {num_questions} fill-in-the-blank questions for a {standard} student on {topic}.
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
|
|
59 |
"""
|
60 |
|
61 |
try:
|
62 |
response = model.predict(prompt).strip() # Ensure clean output
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
current_question["options"].append(line)
|
75 |
-
elif line.startswith("Answer:"):
|
76 |
-
current_question["answer"] = line.split("Answer: ")[1]
|
77 |
-
|
78 |
-
if current_question:
|
79 |
-
questions.append(current_question)
|
80 |
-
|
81 |
-
return questions
|
82 |
except Exception as e:
|
83 |
-
st.error(f"β οΈ
|
84 |
return None
|
85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
# Session state to store quiz data
|
87 |
if 'quiz_data' not in st.session_state:
|
88 |
st.session_state.quiz_data = None
|
@@ -96,52 +119,54 @@ if st.button("π Generate Quiz"):
|
|
96 |
if st.session_state.quiz_data:
|
97 |
st.session_state.user_answers = {} # Reset answers
|
98 |
st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions! π")
|
|
|
99 |
else:
|
100 |
st.error("β οΈ Please enter both the standard and topic.")
|
101 |
|
102 |
# Display Quiz if Available
|
103 |
if st.session_state.quiz_data:
|
104 |
st.write("### π Quiz Questions:")
|
105 |
-
|
|
|
|
|
106 |
st.write(f"**Q{i+1}: {q['question']}**")
|
107 |
|
108 |
if quiz_type == "Multiple Choice Questions (MCQ)":
|
109 |
-
user_answer = st.radio(f"π§ Select your answer for
|
110 |
elif quiz_type == "True or False":
|
111 |
-
user_answer = st.radio(f"π§ Select your answer for
|
112 |
else: # Fill in the Blanks
|
113 |
-
user_answer = st.text_input(f"π§ Your answer for
|
114 |
|
115 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
116 |
|
117 |
# Submit Quiz Button
|
118 |
if st.button("β
Submit Quiz"):
|
119 |
if st.session_state.quiz_data:
|
120 |
-
correct_answers = {f"question_{i+1}": q["answer"].strip().lower() for i, q in enumerate(st.session_state.quiz_data)}
|
121 |
-
score =
|
122 |
-
if user_ans.strip().lower() == correct_answers.get(q_id, ""))
|
123 |
-
|
124 |
|
125 |
st.write("### π― Quiz Results")
|
126 |
st.write(f"Your Score: **{score}/{num_questions}** π")
|
127 |
|
128 |
-
#
|
129 |
-
for q_id, user_ans in
|
130 |
-
|
131 |
-
if
|
132 |
-
st.success(f"β
{
|
133 |
else:
|
134 |
-
st.error(f"β {
|
135 |
|
136 |
# π Animations based on score
|
137 |
-
time.sleep(1)
|
138 |
if score == num_questions:
|
139 |
-
st.snow() #
|
140 |
-
st.success("π Perfect Score! You
|
141 |
elif score / num_questions >= 0.7:
|
142 |
-
st.success("π Great job! Keep practicing!
|
143 |
else:
|
144 |
st.warning("π Don't worry! Learn from mistakes and try again! π")
|
145 |
|
146 |
else:
|
147 |
st.error("β οΈ Quiz data not available. Please regenerate the quiz.")
|
|
|
|
10 |
st.title('π― AI Quiz Generator')
|
11 |
st.subheader('π Test Your Knowledge!')
|
12 |
|
13 |
+
# Input Fields
|
14 |
standard = st.text_input('π Enter Standard/Grade')
|
15 |
topic = st.text_input('π Enter Topic')
|
16 |
+
|
17 |
+
# Quiz Type Selection
|
18 |
quiz_type = st.selectbox("π Select Quiz Type", ["Multiple Choice Questions (MCQ)", "True or False", "Fill in the Blanks"])
|
19 |
+
|
20 |
+
# Difficulty Level Selection
|
21 |
difficulty = st.radio("π Select Difficulty Level", ["Low", "Medium", "Hard"])
|
22 |
+
|
23 |
+
# Number of Questions Selection (1 to 10)
|
24 |
num_questions = st.slider("π’ Select Number of Questions", min_value=1, max_value=10, value=5)
|
25 |
|
26 |
# Initialize AI Model
|
27 |
model = ChatGroq(
|
28 |
temperature=0.6,
|
29 |
groq_api_key=GROQ_API_KEY,
|
30 |
+
model_name="llama-3.3-70b-versatile"
|
31 |
)
|
32 |
|
33 |
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
34 |
+
"""Generate quiz based on user selection and return JSON data."""
|
35 |
+
|
36 |
if quiz_type == "Multiple Choice Questions (MCQ)":
|
37 |
prompt = f"""
|
38 |
Generate {num_questions} multiple choice questions (MCQs) for a {standard} student on {topic}.
|
39 |
Each question should have exactly 4 options (A, B, C, D) and one correct answer.
|
40 |
+
Return the result strictly in the following JSON format:
|
41 |
+
{{
|
42 |
+
"questions": [
|
43 |
+
{{"question": "Question text", "options": ["A) Option 1", "B) Option 2", "C) Option 3", "D) Option 4"], "answer": "A) Option"}}
|
44 |
+
]
|
45 |
+
}}
|
|
|
|
|
|
|
46 |
"""
|
47 |
elif quiz_type == "True or False":
|
48 |
prompt = f"""
|
49 |
Generate {num_questions} True or False questions for a {standard} student on {topic}.
|
50 |
+
Return the result in strict JSON format:
|
51 |
+
{{
|
52 |
+
"questions": [
|
53 |
+
{{"question": "Question text", "answer": "True or False"}}
|
54 |
+
]
|
55 |
+
}}
|
56 |
"""
|
57 |
else: # Fill in the Blanks
|
58 |
prompt = f"""
|
59 |
Generate {num_questions} fill-in-the-blank questions for a {standard} student on {topic}.
|
60 |
+
Provide correct answers in JSON format:
|
61 |
+
{{
|
62 |
+
"questions": [
|
63 |
+
{{"question": "Question with __ blank", "answer": "Correct Answer"}}
|
64 |
+
]
|
65 |
+
}}
|
66 |
"""
|
67 |
|
68 |
try:
|
69 |
response = model.predict(prompt).strip() # Ensure clean output
|
70 |
+
|
71 |
+
# Validate if response is in JSON format
|
72 |
+
quiz_data = json.loads(response)
|
73 |
+
if "questions" in quiz_data:
|
74 |
+
return quiz_data
|
75 |
+
else:
|
76 |
+
st.error("β οΈ The AI did not return a valid quiz format.")
|
77 |
+
return None
|
78 |
+
except json.JSONDecodeError:
|
79 |
+
st.error("β οΈ Failed to generate quiz. The AI did not return a proper JSON response.")
|
80 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
except Exception as e:
|
82 |
+
st.error(f"β οΈ Error: {str(e)}")
|
83 |
return None
|
84 |
|
85 |
+
|
86 |
+
def normalize_answer(answer):
|
87 |
+
"""Convert answers to a standard format for comparison."""
|
88 |
+
answer = answer.strip().lower()
|
89 |
+
if ") " in answer: # Handles cases like "A) Football"
|
90 |
+
answer = answer.split(") ")[0] # Keep only "A", "B", etc.
|
91 |
+
return answer
|
92 |
+
|
93 |
+
def calculate_score(user_answers, correct_answers):
|
94 |
+
"""Calculate score and return details of correct and incorrect answers."""
|
95 |
+
results = []
|
96 |
+
score = 0
|
97 |
+
|
98 |
+
for q, user_ans in user_answers.items():
|
99 |
+
correct_ans = normalize_answer(correct_answers.get(q, ""))
|
100 |
+
user_ans = normalize_answer(user_ans)
|
101 |
+
|
102 |
+
is_correct = user_ans == correct_ans
|
103 |
+
results.append((q, user_ans, correct_ans, is_correct))
|
104 |
+
if is_correct:
|
105 |
+
score += 1
|
106 |
+
|
107 |
+
return score, results
|
108 |
+
|
109 |
# Session state to store quiz data
|
110 |
if 'quiz_data' not in st.session_state:
|
111 |
st.session_state.quiz_data = None
|
|
|
119 |
if st.session_state.quiz_data:
|
120 |
st.session_state.user_answers = {} # Reset answers
|
121 |
st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions! π")
|
122 |
+
st.balloons() # π Balloons for generating the quiz
|
123 |
else:
|
124 |
st.error("β οΈ Please enter both the standard and topic.")
|
125 |
|
126 |
# Display Quiz if Available
|
127 |
if st.session_state.quiz_data:
|
128 |
st.write("### π Quiz Questions:")
|
129 |
+
questions = st.session_state.quiz_data.get("questions", [])
|
130 |
+
|
131 |
+
for i, q in enumerate(questions): # Display all selected questions
|
132 |
st.write(f"**Q{i+1}: {q['question']}**")
|
133 |
|
134 |
if quiz_type == "Multiple Choice Questions (MCQ)":
|
135 |
+
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
|
136 |
elif quiz_type == "True or False":
|
137 |
+
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
|
138 |
else: # Fill in the Blanks
|
139 |
+
user_answer = st.text_input(f"π§ Your answer for Question {i+1}", key=f"question_{i+1}")
|
140 |
|
141 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
142 |
|
143 |
# Submit Quiz Button
|
144 |
if st.button("β
Submit Quiz"):
|
145 |
if st.session_state.quiz_data:
|
146 |
+
correct_answers = {f"question_{i+1}": q["answer"].strip().lower() for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
147 |
+
score, results = calculate_score(st.session_state.user_answers, correct_answers)
|
|
|
|
|
148 |
|
149 |
st.write("### π― Quiz Results")
|
150 |
st.write(f"Your Score: **{score}/{num_questions}** π")
|
151 |
|
152 |
+
# Display Correct Answers
|
153 |
+
for q_id, user_ans, correct_ans, is_correct in results:
|
154 |
+
question_num = q_id.replace("question_", "Question ")
|
155 |
+
if is_correct:
|
156 |
+
st.success(f"β
{question_num} - Correct! ({correct_ans.upper()})")
|
157 |
else:
|
158 |
+
st.error(f"β {question_num} - Incorrect! Your Answer: {user_ans.upper()} | Correct Answer: {correct_ans.upper()}")
|
159 |
|
160 |
# π Animations based on score
|
161 |
+
time.sleep(1) # Small delay for better effect
|
162 |
if score == num_questions:
|
163 |
+
st.snow() # π Trophy effect for a perfect score
|
164 |
+
st.success("π Perfect Score! You are a genius! π")
|
165 |
elif score / num_questions >= 0.7:
|
166 |
+
st.success("π Great job! Keep practicing!")
|
167 |
else:
|
168 |
st.warning("π Don't worry! Learn from mistakes and try again! π")
|
169 |
|
170 |
else:
|
171 |
st.error("β οΈ Quiz data not available. Please regenerate the quiz.")
|
172 |
+
|