Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,24 +4,24 @@ import json
|
|
4 |
import time
|
5 |
|
6 |
# πΉ Groq API Key (Replace with your actual key)
|
7 |
-
GROQ_API_KEY = "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"
|
8 |
|
9 |
# Streamlit App Title
|
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('
|
16 |
|
17 |
# Quiz Type Selection
|
18 |
-
quiz_type = st.selectbox("
|
19 |
|
20 |
# Difficulty Level Selection
|
21 |
-
difficulty = st.radio("
|
22 |
|
23 |
# Number of Questions Selection (1 to 10)
|
24 |
-
num_questions = st.slider("
|
25 |
|
26 |
# Initialize AI Model
|
27 |
model = ChatGroq(
|
@@ -31,43 +31,36 @@ model = ChatGroq(
|
|
31 |
|
32 |
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
33 |
"""Generate quiz based on user selection and return JSON data."""
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
if "MCQ" in quiz_type:
|
40 |
-
prompt = f"Generate {num_questions} MCQs for a {standard} student on {topic}. Each question should have 4 options and one correct answer. Output JSON format: {json.dumps(json_format)}"
|
41 |
-
elif "True or False" in quiz_type:
|
42 |
-
prompt = f"Generate {num_questions} True/False questions for a {standard} student on {topic}. Output JSON format: {json.dumps({'questions': [{'question': 'Sample question?', 'answer': 'True'}]})}"
|
43 |
else: # Fill in the Blanks
|
44 |
-
prompt = f"Generate {num_questions}
|
45 |
|
46 |
try:
|
47 |
-
response = model.predict(prompt)
|
48 |
-
|
49 |
-
st.balloons() # π Balloons animation after quiz generation
|
50 |
-
return quiz_data
|
51 |
except json.JSONDecodeError:
|
52 |
-
st.error("β οΈ The AI did not return a
|
53 |
return None
|
54 |
except Exception as e:
|
55 |
st.error(f"β οΈ Error: {str(e)}")
|
56 |
return None
|
57 |
|
58 |
def calculate_score(user_answers, correct_answers):
|
59 |
-
"""Calculate score and return
|
|
|
60 |
score = 0
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
detailed_results.append((q, ans, correct_ans, is_correct))
|
67 |
if is_correct:
|
68 |
score += 1
|
69 |
|
70 |
-
return score,
|
71 |
|
72 |
# Session state to store quiz data
|
73 |
if 'quiz_data' not in st.session_state:
|
@@ -82,15 +75,16 @@ if st.button("π Generate Quiz"):
|
|
82 |
if st.session_state.quiz_data:
|
83 |
st.session_state.user_answers = {} # Reset answers
|
84 |
st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
|
|
|
85 |
else:
|
86 |
-
st.error("
|
87 |
|
88 |
# Display Quiz if Available
|
89 |
if st.session_state.quiz_data:
|
90 |
st.write("### π Quiz Questions:")
|
91 |
questions = st.session_state.quiz_data.get("questions", [])
|
92 |
|
93 |
-
for i, q in enumerate(questions):
|
94 |
st.write(f"**Q{i+1}: {q['question']}**")
|
95 |
|
96 |
if quiz_type == "Multiple Choice Questions (MCQ)":
|
@@ -98,31 +92,35 @@ if st.session_state.quiz_data:
|
|
98 |
elif quiz_type == "True or False":
|
99 |
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
|
100 |
else: # Fill in the Blanks
|
101 |
-
user_answer = st.text_input(f"
|
102 |
|
103 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
104 |
|
105 |
# Submit Quiz Button
|
106 |
-
if st.button("Submit Quiz"):
|
107 |
if st.session_state.quiz_data:
|
108 |
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
109 |
-
score = calculate_score(st.session_state.user_answers, correct_answers)
|
110 |
|
111 |
-
st.write("### Quiz Results")
|
112 |
-
st.write(f"Your Score: {score}/{num_questions} π")
|
113 |
|
114 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
if score == num_questions:
|
116 |
-
st.
|
117 |
-
st.
|
118 |
-
elif score
|
119 |
-
st.
|
120 |
-
st.markdown("βοΈ **Great Job! Keep Pushing for Perfection!** βοΈ")
|
121 |
else:
|
122 |
-
st.
|
123 |
|
124 |
-
st.success("Great job! Keep practicing!")
|
125 |
else:
|
126 |
-
st.error("Quiz data not available. Please regenerate the quiz.")
|
127 |
-
|
128 |
-
|
|
|
4 |
import time
|
5 |
|
6 |
# πΉ Groq API Key (Replace with your actual key)
|
7 |
+
GROQ_API_KEY = "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"
|
8 |
|
9 |
# Streamlit App Title
|
10 |
st.title('π― AI Quiz Generator')
|
11 |
+
st.subheader('π Test Your Knowledge and Have Fun!')
|
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(
|
|
|
31 |
|
32 |
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
33 |
"""Generate quiz based on user selection and return JSON data."""
|
34 |
+
if quiz_type == "Multiple Choice Questions (MCQ)":
|
35 |
+
prompt = f"Generate {num_questions} multiple choice questions (MCQs) for a {standard} student on {topic}. Each question should have 4 options and one correct answer. Return JSON format: {{'questions': [{{'question': '...', 'options': ['...', '...', '...', '...'], 'answer': '...'}}]}}"
|
36 |
+
elif quiz_type == "True or False":
|
37 |
+
prompt = f"Generate {num_questions} true or false questions for a {standard} student on {topic}. Return JSON format: {{'questions': [{{'question': '...', 'answer': 'True or False'}}]}}"
|
|
|
|
|
|
|
|
|
|
|
38 |
else: # Fill in the Blanks
|
39 |
+
prompt = f"Generate {num_questions} fill-in-the-blank questions for a {standard} student on {topic}. Indicate the correct answer in JSON format: {{'questions': [{{'question': '...', 'answer': '...'}}]}}"
|
40 |
|
41 |
try:
|
42 |
+
response = model.predict(prompt)
|
43 |
+
return json.loads(response) # Parse JSON response safely
|
|
|
|
|
44 |
except json.JSONDecodeError:
|
45 |
+
st.error("β οΈ Failed to generate quiz. The AI did not return a proper JSON response.")
|
46 |
return None
|
47 |
except Exception as e:
|
48 |
st.error(f"β οΈ Error: {str(e)}")
|
49 |
return None
|
50 |
|
51 |
def calculate_score(user_answers, correct_answers):
|
52 |
+
"""Calculate score and return details of correct and incorrect answers."""
|
53 |
+
results = []
|
54 |
score = 0
|
55 |
+
|
56 |
+
for q, user_ans in user_answers.items():
|
57 |
+
correct_ans = correct_answers.get(q, "")
|
58 |
+
is_correct = user_ans == correct_ans
|
59 |
+
results.append((q, user_ans, correct_ans, is_correct))
|
|
|
60 |
if is_correct:
|
61 |
score += 1
|
62 |
|
63 |
+
return score, results
|
64 |
|
65 |
# Session state to store quiz data
|
66 |
if 'quiz_data' not in st.session_state:
|
|
|
75 |
if st.session_state.quiz_data:
|
76 |
st.session_state.user_answers = {} # Reset answers
|
77 |
st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
|
78 |
+
st.balloons() # π Balloons for generating the quiz
|
79 |
else:
|
80 |
+
st.error("β οΈ Please enter both the standard and topic.")
|
81 |
|
82 |
# Display Quiz if Available
|
83 |
if st.session_state.quiz_data:
|
84 |
st.write("### π Quiz Questions:")
|
85 |
questions = st.session_state.quiz_data.get("questions", [])
|
86 |
|
87 |
+
for i, q in enumerate(questions): # Display all selected questions
|
88 |
st.write(f"**Q{i+1}: {q['question']}**")
|
89 |
|
90 |
if quiz_type == "Multiple Choice Questions (MCQ)":
|
|
|
92 |
elif quiz_type == "True or False":
|
93 |
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
|
94 |
else: # Fill in the Blanks
|
95 |
+
user_answer = st.text_input(f"π§ Your answer for Question {i+1}", key=f"question_{i+1}")
|
96 |
|
97 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
98 |
|
99 |
# Submit Quiz Button
|
100 |
+
if st.button("β
Submit Quiz"):
|
101 |
if st.session_state.quiz_data:
|
102 |
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
103 |
+
score, results = calculate_score(st.session_state.user_answers, correct_answers)
|
104 |
|
105 |
+
st.write("### π― Quiz Results")
|
106 |
+
st.write(f"Your Score: **{score}/{num_questions}** π")
|
107 |
|
108 |
+
# Display Correct Answers
|
109 |
+
for q_id, user_ans, correct_ans, is_correct in results:
|
110 |
+
if is_correct:
|
111 |
+
st.success(f"β
{q_id.replace('_', ' ').title()} - Correct! ({correct_ans})")
|
112 |
+
else:
|
113 |
+
st.error(f"β {q_id.replace('_', ' ').title()} - Incorrect! Your Answer: {user_ans} | Correct Answer: {correct_ans}")
|
114 |
+
|
115 |
+
# π Animations based on score
|
116 |
+
time.sleep(1) # Small delay for better effect
|
117 |
if score == num_questions:
|
118 |
+
st.snow() # π Trophy effect for a perfect score
|
119 |
+
st.success("π Perfect Score! You are a genius! π")
|
120 |
+
elif score / num_questions >= 0.7:
|
121 |
+
st.success("π Great job! Keep practicing!")
|
|
|
122 |
else:
|
123 |
+
st.warning("π Don't worry! Learn from mistakes and try again!")
|
124 |
|
|
|
125 |
else:
|
126 |
+
st.error("β οΈ Quiz data not available. Please regenerate the quiz.")
|
|
|
|