Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,31 +3,25 @@ from langchain_groq import ChatGroq
|
|
3 |
import json
|
4 |
import time
|
5 |
|
6 |
-
# πΉ Replace with your actual
|
7 |
GROQ_API_KEY = "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"
|
8 |
|
9 |
-
# Streamlit App Title
|
10 |
-
st.
|
11 |
-
st.
|
12 |
-
|
13 |
-
#
|
14 |
-
|
15 |
-
|
16 |
-
standard = st.text_input('π« Enter Standard/Grade')
|
17 |
-
with col2:
|
18 |
-
topic = st.text_input('π Enter Topic')
|
19 |
-
|
20 |
-
# Quiz Type Selection with Icons
|
21 |
-
quiz_type = st.selectbox(
|
22 |
-
"π Select Quiz Type",
|
23 |
-
["π Multiple Choice Questions (MCQ)", "β
True or False", "βοΈ Fill in the Blanks"]
|
24 |
-
)
|
25 |
|
26 |
-
#
|
27 |
-
|
28 |
|
29 |
-
#
|
30 |
-
|
|
|
|
|
|
|
31 |
|
32 |
# Initialize AI Model
|
33 |
model = ChatGroq(
|
@@ -39,14 +33,10 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
|
39 |
"""Generate quiz based on user selection and return JSON data."""
|
40 |
st.info("β¨ AI is generating your quiz... Please wait!")
|
41 |
|
42 |
-
time.sleep(
|
43 |
|
44 |
# Define structured JSON format instruction
|
45 |
-
json_format = {
|
46 |
-
"questions": [
|
47 |
-
{"question": "Sample question?", "options": ["A", "B", "C", "D"], "answer": "A"}
|
48 |
-
]
|
49 |
-
}
|
50 |
|
51 |
if "MCQ" in quiz_type:
|
52 |
prompt = f"""
|
@@ -68,7 +58,10 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
|
68 |
try:
|
69 |
response = model.predict(prompt) # AI Response
|
70 |
response = response.strip().replace("```json", "").replace("```", "") # Remove formatting if needed
|
71 |
-
|
|
|
|
|
|
|
72 |
except json.JSONDecodeError:
|
73 |
st.error("β οΈ The AI did not return a valid JSON response. Try again!")
|
74 |
return None
|
@@ -76,9 +69,6 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
|
76 |
st.error(f"β οΈ Error: {str(e)}")
|
77 |
return None
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
# Function to Calculate Score
|
82 |
def calculate_score(user_answers, correct_answers):
|
83 |
"""Calculate score based on user answers."""
|
84 |
return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
|
@@ -89,60 +79,49 @@ if 'quiz_data' not in st.session_state:
|
|
89 |
if 'user_answers' not in st.session_state:
|
90 |
st.session_state.user_answers = {}
|
91 |
|
92 |
-
# Generate Quiz Button
|
93 |
if st.button("π Generate Quiz"):
|
94 |
if standard and topic:
|
95 |
-
|
96 |
-
st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
|
97 |
if st.session_state.quiz_data:
|
98 |
st.session_state.user_answers = {} # Reset answers
|
99 |
-
st.success(f"
|
100 |
-
st.balloons()
|
101 |
else:
|
102 |
-
st.error("
|
103 |
|
104 |
# Display Quiz if Available
|
105 |
if st.session_state.quiz_data:
|
106 |
-
st.
|
107 |
questions = st.session_state.quiz_data.get("questions", [])
|
108 |
|
109 |
for i, q in enumerate(questions): # Display all selected questions
|
110 |
st.write(f"**Q{i+1}: {q['question']}**")
|
111 |
|
112 |
-
if "MCQ"
|
113 |
-
user_answer = st.radio(f"
|
114 |
-
elif "True or False"
|
115 |
-
user_answer = st.radio(f"
|
116 |
else: # Fill in the Blanks
|
117 |
-
user_answer = st.text_input(f"
|
118 |
|
119 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
120 |
|
121 |
-
# Submit Quiz Button
|
122 |
-
if st.button("
|
123 |
if st.session_state.quiz_data:
|
124 |
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
125 |
score = calculate_score(st.session_state.user_answers, correct_answers)
|
126 |
|
127 |
-
|
128 |
-
st.
|
129 |
-
|
130 |
-
for percent_complete in range(100):
|
131 |
-
time.sleep(0.01)
|
132 |
-
progress_bar.progress(percent_complete + 1)
|
133 |
-
|
134 |
-
# Score Results
|
135 |
-
st.markdown("<h2 style='color: #8E44AD;'>π Your Quiz Results</h2>", unsafe_allow_html=True)
|
136 |
-
st.write(f"β
**Your Score: {score}/{num_questions} π**")
|
137 |
-
|
138 |
-
# Show different messages based on score
|
139 |
if score == num_questions:
|
140 |
-
st.success("
|
141 |
-
|
142 |
-
|
143 |
-
st.info("π‘ Great job! Keep practicing to improve! πͺ")
|
144 |
else:
|
145 |
-
st.warning("
|
146 |
|
|
|
147 |
else:
|
148 |
-
st.error("
|
|
|
3 |
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 |
+
# User Inputs
|
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(
|
|
|
33 |
"""Generate quiz based on user selection and return JSON data."""
|
34 |
st.info("β¨ AI is generating your quiz... Please wait!")
|
35 |
|
36 |
+
time.sleep(2) # Simulate loading effect
|
37 |
|
38 |
# Define structured JSON format instruction
|
39 |
+
json_format = {"questions": [{"question": "Sample question?", "options": ["A", "B", "C", "D"], "answer": "A"}]}
|
|
|
|
|
|
|
|
|
40 |
|
41 |
if "MCQ" in quiz_type:
|
42 |
prompt = f"""
|
|
|
58 |
try:
|
59 |
response = model.predict(prompt) # AI Response
|
60 |
response = response.strip().replace("```json", "").replace("```", "") # Remove formatting if needed
|
61 |
+
quiz_data = json.loads(response) # Parse JSON safely
|
62 |
+
|
63 |
+
st.balloons() # π Balloons animation after quiz generation
|
64 |
+
return quiz_data
|
65 |
except json.JSONDecodeError:
|
66 |
st.error("β οΈ The AI did not return a valid JSON response. Try again!")
|
67 |
return None
|
|
|
69 |
st.error(f"β οΈ Error: {str(e)}")
|
70 |
return None
|
71 |
|
|
|
|
|
|
|
72 |
def calculate_score(user_answers, correct_answers):
|
73 |
"""Calculate score based on user answers."""
|
74 |
return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
|
|
|
79 |
if 'user_answers' not in st.session_state:
|
80 |
st.session_state.user_answers = {}
|
81 |
|
82 |
+
# Generate Quiz Button
|
83 |
if st.button("π Generate Quiz"):
|
84 |
if standard and topic:
|
85 |
+
st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
|
|
|
86 |
if st.session_state.quiz_data:
|
87 |
st.session_state.user_answers = {} # Reset answers
|
88 |
+
st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
|
|
|
89 |
else:
|
90 |
+
st.error("β Please enter both the standard and topic.")
|
91 |
|
92 |
# Display Quiz if Available
|
93 |
if st.session_state.quiz_data:
|
94 |
+
st.write("### π Quiz Questions:")
|
95 |
questions = st.session_state.quiz_data.get("questions", [])
|
96 |
|
97 |
for i, q in enumerate(questions): # Display all selected questions
|
98 |
st.write(f"**Q{i+1}: {q['question']}**")
|
99 |
|
100 |
+
if quiz_type == "Multiple Choice Questions (MCQ)":
|
101 |
+
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
|
102 |
+
elif quiz_type == "True or False":
|
103 |
+
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
|
104 |
else: # Fill in the Blanks
|
105 |
+
user_answer = st.text_input(f"βοΈ Your answer for Question {i+1}", key=f"question_{i+1}")
|
106 |
|
107 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
108 |
|
109 |
+
# Submit Quiz Button
|
110 |
+
if st.button("π Submit Quiz"):
|
111 |
if st.session_state.quiz_data:
|
112 |
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
113 |
score = calculate_score(st.session_state.user_answers, correct_answers)
|
114 |
|
115 |
+
st.write("### π Quiz Results")
|
116 |
+
st.write(f"π Your Score: **{score}/{num_questions}**")
|
117 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
if score == num_questions:
|
119 |
+
st.success("π₯ Perfect Score! You're a genius! ποΈ")
|
120 |
+
elif score >= num_questions // 2:
|
121 |
+
st.success("π Well done! Keep learning! π")
|
|
|
122 |
else:
|
123 |
+
st.warning("π Try again! You can improve! π‘")
|
124 |
|
125 |
+
st.snow() # π Trophy animation after quiz submission
|
126 |
else:
|
127 |
+
st.error("π¨ Quiz data not available. Please regenerate the quiz.")
|