Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,26 +1,33 @@
|
|
1 |
import streamlit as st
|
2 |
from langchain_groq import ChatGroq
|
3 |
import json
|
|
|
4 |
|
5 |
-
# πΉ
|
6 |
GROQ_API_KEY = "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"
|
7 |
|
8 |
-
# Streamlit App Title
|
9 |
-
st.
|
10 |
-
st.
|
11 |
-
|
12 |
-
# Input Fields
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
# Difficulty Level Selection
|
20 |
-
difficulty = st.radio("Select Difficulty Level", ["
|
21 |
|
22 |
-
# Number of Questions Selection (1 to 10)
|
23 |
-
num_questions = st.slider("Select Number of Questions", min_value=1, max_value=10, value=5)
|
24 |
|
25 |
# Initialize AI Model
|
26 |
model = ChatGroq(
|
@@ -28,18 +35,22 @@ model = ChatGroq(
|
|
28 |
groq_api_key=GROQ_API_KEY
|
29 |
)
|
30 |
|
|
|
31 |
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
32 |
"""Generate quiz based on user selection and return JSON data."""
|
33 |
-
|
|
|
|
|
|
|
|
|
34 |
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': '...'}}]}}"
|
35 |
-
elif
|
36 |
prompt = f"Generate {num_questions} true or false questions for a {standard} student on {topic}. Return JSON format: {{'questions': [{{'question': '...', 'answer': 'True or False'}}]}}"
|
37 |
else: # Fill in the Blanks
|
38 |
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': '...'}}]}}"
|
39 |
|
40 |
try:
|
41 |
response = model.predict(prompt)
|
42 |
-
st.write("πΉ **Raw API Response:**", response) # Debugging
|
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.")
|
@@ -48,7 +59,7 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
|
48 |
st.error(f"β οΈ Error: {str(e)}")
|
49 |
return None
|
50 |
|
51 |
-
|
52 |
def calculate_score(user_answers, correct_answers):
|
53 |
"""Calculate score based on user answers."""
|
54 |
return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
|
@@ -59,41 +70,60 @@ if 'quiz_data' not in st.session_state:
|
|
59 |
if 'user_answers' not in st.session_state:
|
60 |
st.session_state.user_answers = {}
|
61 |
|
62 |
-
# Generate Quiz Button
|
63 |
-
if st.button("Generate Quiz"):
|
64 |
if standard and topic:
|
65 |
-
st.
|
|
|
66 |
if st.session_state.quiz_data:
|
67 |
st.session_state.user_answers = {} # Reset answers
|
68 |
-
st.success(f"{quiz_type} Quiz
|
|
|
69 |
else:
|
70 |
-
st.error("Please enter both the
|
71 |
|
72 |
# Display Quiz if Available
|
73 |
if st.session_state.quiz_data:
|
74 |
-
st.
|
75 |
questions = st.session_state.quiz_data.get("questions", [])
|
76 |
|
77 |
for i, q in enumerate(questions): # Display all selected questions
|
78 |
st.write(f"**Q{i+1}: {q['question']}**")
|
79 |
|
80 |
-
if
|
81 |
-
user_answer = st.radio(f"Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
|
82 |
-
elif
|
83 |
-
user_answer = st.radio(f"Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
|
84 |
else: # Fill in the Blanks
|
85 |
-
user_answer = st.text_input(f"Your answer for Question {i+1}", key=f"question_{i+1}")
|
86 |
|
87 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
88 |
|
89 |
-
# Submit Quiz Button
|
90 |
-
if st.button("Submit Quiz"):
|
91 |
if st.session_state.quiz_data:
|
92 |
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
93 |
score = calculate_score(st.session_state.user_answers, correct_answers)
|
94 |
|
95 |
-
|
96 |
-
st.
|
97 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
else:
|
99 |
-
st.error("Quiz data not available. Please regenerate the quiz.")
|
|
|
1 |
import streamlit as st
|
2 |
from langchain_groq import ChatGroq
|
3 |
import json
|
4 |
+
import time
|
5 |
|
6 |
+
# πΉ Replace with your actual API key
|
7 |
GROQ_API_KEY = "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"
|
8 |
|
9 |
+
# Streamlit App Title with Animation
|
10 |
+
st.markdown("<h1 style='text-align: center; color: #FF5733;'>π― AI Quiz Generator π</h1>", unsafe_allow_html=True)
|
11 |
+
st.markdown("<h3 style='text-align: center; color: #3498db;'>Test Your Knowledge with Fun Quizzes!</h3>", unsafe_allow_html=True)
|
12 |
+
|
13 |
+
# Input Fields with Side-by-Side Layout
|
14 |
+
col1, col2 = st.columns(2)
|
15 |
+
with col1:
|
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 |
+
# Difficulty Level Selection with Emojis
|
27 |
+
difficulty = st.radio("π₯ Select Difficulty Level", ["π Easy", "π Medium", "πͺ Hard"])
|
28 |
|
29 |
+
# Number of Questions Selection (1 to 10) with Emoji
|
30 |
+
num_questions = st.slider("π’ Select Number of Questions", min_value=1, max_value=10, value=5)
|
31 |
|
32 |
# Initialize AI Model
|
33 |
model = ChatGroq(
|
|
|
35 |
groq_api_key=GROQ_API_KEY
|
36 |
)
|
37 |
|
38 |
+
# Function to Generate Quiz
|
39 |
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
40 |
"""Generate quiz based on user selection and return JSON data."""
|
41 |
+
st.info("β¨ AI is generating your quiz... Please wait!") # Show animated loading message
|
42 |
+
|
43 |
+
time.sleep(1) # Simulate loading effect
|
44 |
+
|
45 |
+
if "MCQ" in quiz_type:
|
46 |
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': '...'}}]}}"
|
47 |
+
elif "True or False" in quiz_type:
|
48 |
prompt = f"Generate {num_questions} true or false questions for a {standard} student on {topic}. Return JSON format: {{'questions': [{{'question': '...', 'answer': 'True or False'}}]}}"
|
49 |
else: # Fill in the Blanks
|
50 |
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': '...'}}]}}"
|
51 |
|
52 |
try:
|
53 |
response = model.predict(prompt)
|
|
|
54 |
return json.loads(response) # Parse JSON response safely
|
55 |
except json.JSONDecodeError:
|
56 |
st.error("β οΈ Failed to generate quiz. The AI did not return a proper JSON response.")
|
|
|
59 |
st.error(f"β οΈ Error: {str(e)}")
|
60 |
return None
|
61 |
|
62 |
+
# Function to Calculate Score
|
63 |
def calculate_score(user_answers, correct_answers):
|
64 |
"""Calculate score based on user answers."""
|
65 |
return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
|
|
|
70 |
if 'user_answers' not in st.session_state:
|
71 |
st.session_state.user_answers = {}
|
72 |
|
73 |
+
# Generate Quiz Button with Animation
|
74 |
+
if st.button("π Generate Quiz"):
|
75 |
if standard and topic:
|
76 |
+
with st.spinner("π AI is thinking... Generating your quiz!"):
|
77 |
+
st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
|
78 |
if st.session_state.quiz_data:
|
79 |
st.session_state.user_answers = {} # Reset answers
|
80 |
+
st.success(f"π {quiz_type} Quiz with {num_questions} Questions Generated Successfully!")
|
81 |
+
st.balloons()
|
82 |
else:
|
83 |
+
st.error("β οΈ Please enter both the Standard and Topic.")
|
84 |
|
85 |
# Display Quiz if Available
|
86 |
if st.session_state.quiz_data:
|
87 |
+
st.markdown("<h3 style='color: #2ECC71;'>π Your Quiz Questions:</h3>", unsafe_allow_html=True)
|
88 |
questions = st.session_state.quiz_data.get("questions", [])
|
89 |
|
90 |
for i, q in enumerate(questions): # Display all selected questions
|
91 |
st.write(f"**Q{i+1}: {q['question']}**")
|
92 |
|
93 |
+
if "MCQ" in quiz_type:
|
94 |
+
user_answer = st.radio(f"π― Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
|
95 |
+
elif "True or False" in quiz_type:
|
96 |
+
user_answer = st.radio(f"β
Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
|
97 |
else: # Fill in the Blanks
|
98 |
+
user_answer = st.text_input(f"βοΈ Your answer for Question {i+1}", key=f"question_{i+1}")
|
99 |
|
100 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
101 |
|
102 |
+
# Submit Quiz Button with Animated Score Display
|
103 |
+
if st.button("π Submit Quiz"):
|
104 |
if st.session_state.quiz_data:
|
105 |
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
106 |
score = calculate_score(st.session_state.user_answers, correct_answers)
|
107 |
|
108 |
+
# Animated Progress Bar
|
109 |
+
st.markdown("<h3 style='color: #F39C12;'>β³ Calculating Score...</h3>", unsafe_allow_html=True)
|
110 |
+
progress_bar = st.progress(0)
|
111 |
+
for percent_complete in range(100):
|
112 |
+
time.sleep(0.01)
|
113 |
+
progress_bar.progress(percent_complete + 1)
|
114 |
+
|
115 |
+
# Score Results
|
116 |
+
st.markdown("<h2 style='color: #8E44AD;'>π Your Quiz Results</h2>", unsafe_allow_html=True)
|
117 |
+
st.write(f"β
**Your Score: {score}/{num_questions} π**")
|
118 |
+
|
119 |
+
# Show different messages based on score
|
120 |
+
if score == num_questions:
|
121 |
+
st.success("π Perfect Score! You're a genius! π")
|
122 |
+
st.balloons()
|
123 |
+
elif score >= num_questions / 2:
|
124 |
+
st.info("π‘ Great job! Keep practicing to improve! πͺ")
|
125 |
+
else:
|
126 |
+
st.warning("π Don't worry! Try again and improve your score! π")
|
127 |
+
|
128 |
else:
|
129 |
+
st.error("β οΈ Quiz data not available. Please regenerate the quiz.")
|