Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,144 +3,114 @@ from langchain_groq import ChatGroq
|
|
3 |
import json
|
4 |
import time
|
5 |
|
6 |
-
#
|
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('π Enter Topic')
|
16 |
|
17 |
-
#
|
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
|
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
|
35 |
-
|
36 |
-
|
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 |
-
|
69 |
-
|
|
|
|
|
|
|
70 |
|
71 |
-
|
|
|
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("β οΈ
|
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 |
-
"""
|
88 |
-
|
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
|
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 |
-
#
|
110 |
if 'quiz_data' not in st.session_state:
|
111 |
st.session_state.quiz_data = None
|
112 |
if 'user_answers' not in st.session_state:
|
113 |
st.session_state.user_answers = {}
|
114 |
|
115 |
-
# Generate Quiz Button
|
116 |
if st.button("π Generate Quiz"):
|
117 |
if standard and topic:
|
118 |
-
|
|
|
119 |
if st.session_state.quiz_data:
|
120 |
-
st.session_state.user_answers = {}
|
121 |
-
st.success(f"{
|
122 |
-
st.balloons()
|
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):
|
132 |
st.write(f"**Q{i+1}: {q['question']}**")
|
133 |
|
134 |
-
if
|
135 |
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
|
136 |
-
|
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"])}
|
@@ -149,7 +119,7 @@ if st.button("β
Submit Quiz"):
|
|
149 |
st.write("### π― Quiz Results")
|
150 |
st.write(f"Your Score: **{score}/{num_questions}** π")
|
151 |
|
152 |
-
#
|
153 |
for q_id, user_ans, correct_ans, is_correct in results:
|
154 |
question_num = q_id.replace("question_", "Question ")
|
155 |
if is_correct:
|
@@ -157,10 +127,10 @@ if st.button("β
Submit Quiz"):
|
|
157 |
else:
|
158 |
st.error(f"β {question_num} - Incorrect! Your Answer: {user_ans.upper()} | Correct Answer: {correct_ans.upper()}")
|
159 |
|
160 |
-
#
|
161 |
-
time.sleep(1)
|
162 |
if score == num_questions:
|
163 |
-
st.snow()
|
164 |
st.success("π Perfect Score! You are a genius! π")
|
165 |
elif score / num_questions >= 0.7:
|
166 |
st.success("π Great job! Keep practicing!")
|
@@ -170,3 +140,4 @@ if st.button("β
Submit Quiz"):
|
|
170 |
else:
|
171 |
st.error("β οΈ Quiz data not available. Please regenerate the quiz.")
|
172 |
|
|
|
|
3 |
import json
|
4 |
import time
|
5 |
|
6 |
+
# π― 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 |
+
# πΉ Difficulty Level
|
|
|
|
|
|
|
18 |
difficulty = st.radio("π Select Difficulty Level", ["Low", "Medium", "Hard"])
|
19 |
|
20 |
+
# πΉ Number of Questions (1-10)
|
21 |
num_questions = st.slider("π’ Select Number of Questions", min_value=1, max_value=10, value=5)
|
22 |
|
23 |
+
# πΉ Initialize AI Model
|
24 |
model = ChatGroq(
|
25 |
temperature=0.6,
|
26 |
groq_api_key=GROQ_API_KEY,
|
27 |
+
model_name="llama-3.3-70b-versatile"
|
28 |
)
|
29 |
|
30 |
+
def detect_quiz_type(topic):
|
31 |
+
"""AI determines the best quiz type for the topic."""
|
32 |
+
prompt = f"""
|
33 |
+
Given the topic '{topic}', select the most suitable quiz type:
|
34 |
+
- 'MCQ' for subjects like Science, Math, History.
|
35 |
+
- 'True/False' for fact-based topics.
|
36 |
+
- 'Fill in the Blanks' for language-based topics.
|
37 |
+
|
38 |
+
Return only one of these: "MCQ", "True/False", "Fill in the Blanks".
|
39 |
+
"""
|
40 |
+
response = model.predict(prompt).strip()
|
41 |
+
if response in ["MCQ", "True/False", "Fill in the Blanks"]:
|
42 |
+
return response
|
43 |
+
return "MCQ" # Default to MCQ
|
44 |
+
|
45 |
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
|
46 |
+
"""Generate quiz using AI with strict JSON formatting."""
|
47 |
+
prompt = f"""
|
48 |
+
Generate {num_questions} {quiz_type} questions for a {standard} student on {topic}.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
+
Format:
|
51 |
+
{{"questions": [
|
52 |
+
{{"question": "Example?", "options": ["A) Option1", "B) Option2"], "answer": "A) Option1"}}
|
53 |
+
]}}
|
54 |
+
"""
|
55 |
|
56 |
+
try:
|
57 |
+
response = model.predict(prompt).strip()
|
58 |
quiz_data = json.loads(response)
|
59 |
+
return quiz_data if "questions" in quiz_data else None
|
|
|
|
|
|
|
|
|
60 |
except json.JSONDecodeError:
|
61 |
+
st.error("β οΈ AI response is not valid JSON. Try again!")
|
|
|
|
|
|
|
62 |
return None
|
63 |
|
|
|
64 |
def normalize_answer(answer):
|
65 |
+
"""Standardize answers for case-insensitive comparison."""
|
66 |
+
return answer.strip().lower()
|
|
|
|
|
|
|
67 |
|
68 |
def calculate_score(user_answers, correct_answers):
|
69 |
+
"""Calculate quiz score and return result details."""
|
70 |
+
results, score = [], 0
|
|
|
|
|
71 |
for q, user_ans in user_answers.items():
|
72 |
correct_ans = normalize_answer(correct_answers.get(q, ""))
|
73 |
user_ans = normalize_answer(user_ans)
|
|
|
74 |
is_correct = user_ans == correct_ans
|
75 |
results.append((q, user_ans, correct_ans, is_correct))
|
76 |
if is_correct:
|
77 |
score += 1
|
|
|
78 |
return score, results
|
79 |
|
80 |
+
# πΉ Store Quiz Data in Session
|
81 |
if 'quiz_data' not in st.session_state:
|
82 |
st.session_state.quiz_data = None
|
83 |
if 'user_answers' not in st.session_state:
|
84 |
st.session_state.user_answers = {}
|
85 |
|
86 |
+
# πΉ Generate Quiz Button
|
87 |
if st.button("π Generate Quiz"):
|
88 |
if standard and topic:
|
89 |
+
auto_quiz_type = detect_quiz_type(topic) # AI selects quiz type
|
90 |
+
st.session_state.quiz_data = generate_quiz(standard, topic, auto_quiz_type, difficulty, num_questions)
|
91 |
if st.session_state.quiz_data:
|
92 |
+
st.session_state.user_answers = {}
|
93 |
+
st.success(f"β
{auto_quiz_type} Quiz Generated on '{topic}' with {num_questions} Questions!")
|
94 |
+
st.balloons()
|
95 |
else:
|
96 |
st.error("β οΈ Please enter both the standard and topic.")
|
97 |
|
98 |
+
# πΉ Display Quiz if Available
|
99 |
if st.session_state.quiz_data:
|
100 |
st.write("### π Quiz Questions:")
|
101 |
questions = st.session_state.quiz_data.get("questions", [])
|
102 |
|
103 |
+
for i, q in enumerate(questions):
|
104 |
st.write(f"**Q{i+1}: {q['question']}**")
|
105 |
|
106 |
+
if "options" in q:
|
107 |
user_answer = st.radio(f"π§ Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
|
108 |
+
else:
|
|
|
|
|
109 |
user_answer = st.text_input(f"π§ Your answer for Question {i+1}", key=f"question_{i+1}")
|
110 |
|
111 |
st.session_state.user_answers[f"question_{i+1}"] = user_answer
|
112 |
|
113 |
+
# πΉ Submit Quiz Button
|
114 |
if st.button("β
Submit Quiz"):
|
115 |
if st.session_state.quiz_data:
|
116 |
correct_answers = {f"question_{i+1}": q["answer"].strip().lower() for i, q in enumerate(st.session_state.quiz_data["questions"])}
|
|
|
119 |
st.write("### π― Quiz Results")
|
120 |
st.write(f"Your Score: **{score}/{num_questions}** π")
|
121 |
|
122 |
+
# πΉ Show Correct/Incorrect Answers
|
123 |
for q_id, user_ans, correct_ans, is_correct in results:
|
124 |
question_num = q_id.replace("question_", "Question ")
|
125 |
if is_correct:
|
|
|
127 |
else:
|
128 |
st.error(f"β {question_num} - Incorrect! Your Answer: {user_ans.upper()} | Correct Answer: {correct_ans.upper()}")
|
129 |
|
130 |
+
# πΉ Animations Based on Score
|
131 |
+
time.sleep(1)
|
132 |
if score == num_questions:
|
133 |
+
st.snow()
|
134 |
st.success("π Perfect Score! You are a genius! π")
|
135 |
elif score / num_questions >= 0.7:
|
136 |
st.success("π Great job! Keep practicing!")
|
|
|
140 |
else:
|
141 |
st.error("β οΈ Quiz data not available. Please regenerate the quiz.")
|
142 |
|
143 |
+
|