Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,114 +2,93 @@ import streamlit as st
|
|
2 |
from langchain_groq import ChatGroq
|
3 |
import json
|
4 |
|
5 |
-
#
|
6 |
-
st.
|
7 |
|
8 |
-
#
|
9 |
-
st.title(
|
10 |
-
st.subheader(
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
|
15 |
|
16 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
model = ChatGroq(
|
18 |
temperature=0.6,
|
19 |
-
groq_api_key=
|
20 |
)
|
21 |
|
22 |
-
def generate_quiz(standard, topic, difficulty):
|
23 |
-
"""
|
24 |
-
|
25 |
-
|
26 |
-
""
|
27 |
-
|
28 |
-
|
29 |
-
"
|
30 |
-
|
31 |
-
"{ \"questions\": [ {\"question\": \"...\", \"options\": [\"...\", \"...\", \"...\", \"...\"], \"answer\": \"...\"} ] }"
|
32 |
-
)
|
33 |
response = model.predict(prompt)
|
34 |
try:
|
35 |
-
return json.loads(response)
|
36 |
except json.JSONDecodeError:
|
37 |
-
st.error("
|
38 |
return None
|
39 |
|
40 |
def calculate_score(user_answers, correct_answers):
|
41 |
-
"""Calculate
|
42 |
return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
|
43 |
|
44 |
-
# Session state
|
45 |
-
if
|
46 |
st.session_state.quiz_data = None
|
47 |
-
if
|
48 |
st.session_state.user_answers = {}
|
49 |
-
if "quiz_submitted" not in st.session_state:
|
50 |
-
st.session_state.quiz_submitted = False
|
51 |
-
|
52 |
-
# Difficulty Selection
|
53 |
-
difficulty = st.radio("π― Select Difficulty Level", ["Low", "Medium", "Hard"])
|
54 |
|
55 |
# Generate Quiz Button
|
56 |
-
if st.button("
|
57 |
-
if
|
58 |
-
st.session_state.quiz_data = generate_quiz(
|
59 |
if st.session_state.quiz_data:
|
60 |
-
st.session_state.user_answers = {} # Reset
|
61 |
-
st.
|
62 |
-
st.success("β
Quiz Generated! Scroll down to answer the questions.")
|
63 |
else:
|
64 |
-
st.error("
|
65 |
|
66 |
# Display Quiz if Available
|
67 |
if st.session_state.quiz_data:
|
68 |
-
st.write("
|
69 |
questions = st.session_state.quiz_data.get("questions", [])
|
70 |
|
71 |
-
for i, q in enumerate(questions
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
)
|
78 |
-
|
|
|
|
|
|
|
79 |
|
80 |
# Submit Quiz Button
|
81 |
-
if st.button("
|
82 |
if st.session_state.quiz_data:
|
83 |
-
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"]
|
84 |
score = calculate_score(st.session_state.user_answers, correct_answers)
|
85 |
|
86 |
-
st.
|
87 |
-
st.
|
88 |
-
|
89 |
-
# Display Results After Submission
|
90 |
-
if st.session_state.quiz_submitted:
|
91 |
-
st.write("## π― Quiz Results")
|
92 |
-
|
93 |
-
# Display correct and user answers side by side
|
94 |
-
col1, col2 = st.columns(2)
|
95 |
-
with col1:
|
96 |
-
st.write("### β
Correct Answers")
|
97 |
-
for i, q in enumerate(st.session_state.quiz_data["questions"][:5]):
|
98 |
-
st.write(f"**Q{i+1}:** {q['answer']}")
|
99 |
-
|
100 |
-
with col2:
|
101 |
-
st.write("### π Your Answers")
|
102 |
-
for i, ans in st.session_state.user_answers.items():
|
103 |
-
st.write(f"**{i.replace('_', ' ').title()}:** {ans}")
|
104 |
-
|
105 |
-
# Final Score Display
|
106 |
-
st.markdown(f"## π Your Score: **{st.session_state.score}/5**")
|
107 |
-
|
108 |
-
# Feedback Message
|
109 |
-
if st.session_state.score == 5:
|
110 |
-
st.success("π₯ Perfect! You're a genius!")
|
111 |
-
elif st.session_state.score >= 3:
|
112 |
-
st.info("π Great job! Keep practicing.")
|
113 |
else:
|
114 |
-
st.
|
115 |
-
|
|
|
2 |
from langchain_groq import ChatGroq
|
3 |
import json
|
4 |
|
5 |
+
# Securely Load API Key (Replace with your actual key if not using secrets)
|
6 |
+
GROQ_API_KEY = st.secrets.get("groq_api_key", "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")
|
7 |
|
8 |
+
# Streamlit App Title
|
9 |
+
st.title('AI Quiz Generator π―')
|
10 |
+
st.subheader('Test Your Knowledge!')
|
11 |
|
12 |
+
# Input Fields
|
13 |
+
standard = st.text_input('Enter Standard/Grade')
|
14 |
+
topic = st.text_input('Enter Topic')
|
15 |
|
16 |
+
# Quiz Type Selection
|
17 |
+
quiz_type = st.selectbox("Select Quiz Type", ["Multiple Choice Questions (MCQ)", "True or False", "Fill in the Blanks"])
|
18 |
+
|
19 |
+
# Difficulty Level Selection
|
20 |
+
difficulty = st.radio("Select Difficulty Level", ["Low", "Medium", "Hard"])
|
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(
|
27 |
temperature=0.6,
|
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 |
+
if quiz_type == "Multiple Choice Questions (MCQ)":
|
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 quiz_type == "True or False":
|
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 |
response = model.predict(prompt)
|
41 |
try:
|
42 |
+
return json.loads(response) # Parse JSON response safely
|
43 |
except json.JSONDecodeError:
|
44 |
+
st.error("Failed to generate quiz. Try again.")
|
45 |
return None
|
46 |
|
47 |
def calculate_score(user_answers, correct_answers):
|
48 |
+
"""Calculate score based on user answers."""
|
49 |
return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
|
50 |
|
51 |
+
# Session state to store quiz data
|
52 |
+
if 'quiz_data' not in st.session_state:
|
53 |
st.session_state.quiz_data = None
|
54 |
+
if 'user_answers' not in st.session_state:
|
55 |
st.session_state.user_answers = {}
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
# Generate Quiz Button
|
58 |
+
if st.button("Generate Quiz"):
|
59 |
+
if standard and topic:
|
60 |
+
st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
|
61 |
if st.session_state.quiz_data:
|
62 |
+
st.session_state.user_answers = {} # Reset answers
|
63 |
+
st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
|
|
|
64 |
else:
|
65 |
+
st.error("Please enter both the standard and topic.")
|
66 |
|
67 |
# Display Quiz if Available
|
68 |
if st.session_state.quiz_data:
|
69 |
+
st.write("### Quiz Questions:")
|
70 |
questions = st.session_state.quiz_data.get("questions", [])
|
71 |
|
72 |
+
for i, q in enumerate(questions): # Display all selected questions
|
73 |
+
st.write(f"**Q{i+1}: {q['question']}**")
|
74 |
+
|
75 |
+
if quiz_type == "Multiple Choice Questions (MCQ)":
|
76 |
+
user_answer = st.radio(f"Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
|
77 |
+
elif quiz_type == "True or False":
|
78 |
+
user_answer = st.radio(f"Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
|
79 |
+
else: # Fill in the Blanks
|
80 |
+
user_answer = st.text_input(f"Your answer for Question {i+1}", key=f"question_{i+1}")
|
81 |
+
|
82 |
+
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
83 |
|
84 |
# Submit Quiz Button
|
85 |
+
if st.button("Submit Quiz"):
|
86 |
if st.session_state.quiz_data:
|
87 |
+
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
88 |
score = calculate_score(st.session_state.user_answers, correct_answers)
|
89 |
|
90 |
+
st.write("### Quiz Results")
|
91 |
+
st.write(f"Your Score: {score}/{num_questions} π")
|
92 |
+
st.success("Great job! Keep practicing!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
else:
|
94 |
+
st.error("Quiz data not available. Please regenerate the quiz.")
|
|