harshith1411 commited on
Commit
939aeee
Β·
verified Β·
1 Parent(s): 649e82c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -78
app.py CHANGED
@@ -10,97 +10,79 @@ GROQ_API_KEY = "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"
10
  st.title('🎯 AI Quiz Generator')
11
  st.subheader('πŸš€ Test Your Knowledge!')
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(
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 based on user selection and return JSON data."""
35
-
36
  if quiz_type == "Multiple Choice Questions (MCQ)":
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": "Correct Option (e.g., A)"}}
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
  try:
69
  response = model.predict(prompt).strip() # Ensure clean output
70
-
71
- # πŸ”Ή Hidden raw API response (for debugging, uncomment below if needed)
72
- # st.write("πŸ”Ή **Raw API Response:**", response)
73
-
74
- # Validate if response is in JSON format
75
- quiz_data = json.loads(response)
76
- if "questions" in quiz_data:
77
- return quiz_data
78
- else:
79
- st.error("⚠️ The AI did not return a valid quiz format.")
80
- return None
81
- except json.JSONDecodeError:
82
- st.error("⚠️ Failed to generate quiz. The AI did not return a proper JSON response.")
83
- return None
 
 
 
 
 
84
  except Exception as e:
85
- st.error(f"⚠️ Error: {str(e)}")
86
  return None
87
 
88
-
89
- def calculate_score(user_answers, correct_answers):
90
- """Calculate score and return details of correct and incorrect answers."""
91
- results = []
92
- score = 0
93
-
94
- for q, user_ans in user_answers.items():
95
- correct_ans = correct_answers.get(q, "").strip().lower()
96
- user_ans = user_ans.strip().lower()
97
- is_correct = user_ans == correct_ans
98
- results.append((q, user_ans, correct_ans, is_correct))
99
- if is_correct:
100
- score += 1
101
-
102
- return score, results
103
-
104
  # Session state to store quiz data
105
  if 'quiz_data' not in st.session_state:
106
  st.session_state.quiz_data = None
@@ -114,53 +96,50 @@ if st.button("πŸš€ Generate Quiz"):
114
  if st.session_state.quiz_data:
115
  st.session_state.user_answers = {} # Reset answers
116
  st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions! πŸŽ‰")
117
- st.balloons() # 🎈 Balloons for generating the quiz
118
  else:
119
  st.error("⚠️ Please enter both the standard and topic.")
120
 
121
  # Display Quiz if Available
122
  if st.session_state.quiz_data:
123
  st.write("### πŸ“ Quiz Questions:")
124
- questions = st.session_state.quiz_data.get("questions", [])
125
-
126
- for i, q in enumerate(questions): # Display all selected questions
127
  st.write(f"**Q{i+1}: {q['question']}**")
128
 
129
  if quiz_type == "Multiple Choice Questions (MCQ)":
130
- user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
131
  elif quiz_type == "True or False":
132
- user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
133
  else: # Fill in the Blanks
134
- user_answer = st.text_input(f"🧐 Your answer for Question {i+1}", key=f"question_{i+1}")
135
 
136
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
137
 
138
  # Submit Quiz Button
139
  if st.button("βœ… Submit Quiz"):
140
  if st.session_state.quiz_data:
141
- correct_answers = {f"question_{i+1}": q["answer"].strip().lower() for i, q in enumerate(st.session_state.quiz_data["questions"])}
142
- score, results = calculate_score(st.session_state.user_answers, correct_answers)
143
 
144
  st.write("### 🎯 Quiz Results")
145
  st.write(f"Your Score: **{score}/{num_questions}** πŸŽ‰")
146
 
147
- # Display Correct Answers
148
- for q_id, user_ans, correct_ans, is_correct in results:
149
- if is_correct:
150
- st.success(f"βœ… {q_id.replace('_', ' ').title()} - Correct! ({correct_ans.upper()})")
 
151
  else:
152
- st.error(f"❌ {q_id.replace('_', ' ').title()} - Incorrect! Your Answer: {user_ans.upper()} | Correct Answer: {correct_ans.upper()}")
153
 
154
  # πŸŽ‰ Animations based on score
155
- time.sleep(1) # Small delay for better effect
156
  if score == num_questions:
157
- st.snow() # πŸ† Trophy effect for a perfect score
158
- st.success("πŸ† Perfect Score! You are a genius! πŸš€")
159
  elif score / num_questions >= 0.7:
160
- st.success("πŸŽ‰ Great job! Keep practicing!")
161
  else:
162
  st.warning("πŸ˜ƒ Don't worry! Learn from mistakes and try again! πŸ“š")
163
 
164
  else:
165
  st.error("⚠️ Quiz data not available. Please regenerate the quiz.")
166
-
 
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
  quiz_type = st.selectbox("🎭 Select Quiz Type", ["Multiple Choice Questions (MCQ)", "True or False", "Fill in the Blanks"])
 
 
17
  difficulty = st.radio("πŸ“Š Select Difficulty Level", ["Low", "Medium", "Hard"])
 
 
18
  num_questions = st.slider("πŸ”’ Select Number of Questions", min_value=1, max_value=10, value=5)
19
 
20
  # Initialize AI Model
21
  model = ChatGroq(
22
  temperature=0.6,
23
  groq_api_key=GROQ_API_KEY,
24
+ model_name="llama-3.3-70b-versatile"
25
  )
26
 
27
  def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
28
+ """Generate quiz questions dynamically based on user selection."""
29
+
30
  if quiz_type == "Multiple Choice Questions (MCQ)":
31
  prompt = f"""
32
  Generate {num_questions} multiple choice questions (MCQs) for a {standard} student on {topic}.
33
  Each question should have exactly 4 options (A, B, C, D) and one correct answer.
34
+ Return the result in this format:
35
+
36
+ 1. Question text?
37
+ A) Option 1
38
+ B) Option 2
39
+ C) Option 3
40
+ D) Option 4
41
+
42
+ Answer: Correct Option (A, B, C, or D)
43
  """
44
  elif quiz_type == "True or False":
45
  prompt = f"""
46
  Generate {num_questions} True or False questions for a {standard} student on {topic}.
47
+ Return the result in this format:
48
+
49
+ 1. Question text?
50
+ Answer: True or False
 
 
51
  """
52
  else: # Fill in the Blanks
53
  prompt = f"""
54
  Generate {num_questions} fill-in-the-blank questions for a {standard} student on {topic}.
55
+ Return the result in this format:
56
+
57
+ 1. The capital of France is __.
58
+ Answer: Paris
 
 
59
  """
60
 
61
  try:
62
  response = model.predict(prompt).strip() # Ensure clean output
63
+ quiz_lines = response.split("\n") # Split response into lines
64
+ questions = []
65
+ current_question = None
66
+
67
+ for line in quiz_lines:
68
+ if line.strip() and not line.startswith("Answer:"):
69
+ if line[0].isdigit(): # New question detected
70
+ if current_question:
71
+ questions.append(current_question)
72
+ current_question = {"question": line, "options": [], "answer": ""}
73
+ elif line[0] in "ABCD)" and quiz_type == "Multiple Choice Questions (MCQ)":
74
+ current_question["options"].append(line)
75
+ elif line.startswith("Answer:"):
76
+ current_question["answer"] = line.split("Answer: ")[1]
77
+
78
+ if current_question:
79
+ questions.append(current_question)
80
+
81
+ return questions
82
  except Exception as e:
83
+ st.error(f"⚠️ Failed to generate quiz. Error: {str(e)}")
84
  return None
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  # Session state to store quiz data
87
  if 'quiz_data' not in st.session_state:
88
  st.session_state.quiz_data = None
 
96
  if st.session_state.quiz_data:
97
  st.session_state.user_answers = {} # Reset answers
98
  st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions! πŸŽ‰")
 
99
  else:
100
  st.error("⚠️ Please enter both the standard and topic.")
101
 
102
  # Display Quiz if Available
103
  if st.session_state.quiz_data:
104
  st.write("### πŸ“ Quiz Questions:")
105
+ for i, q in enumerate(st.session_state.quiz_data):
 
 
106
  st.write(f"**Q{i+1}: {q['question']}**")
107
 
108
  if quiz_type == "Multiple Choice Questions (MCQ)":
109
+ user_answer = st.radio(f"🧐 Select your answer for Q{i+1}", options=q["options"], key=f"question_{i+1}")
110
  elif quiz_type == "True or False":
111
+ user_answer = st.radio(f"🧐 Select your answer for Q{i+1}", options=["True", "False"], key=f"question_{i+1}")
112
  else: # Fill in the Blanks
113
+ user_answer = st.text_input(f"🧐 Your answer for Q{i+1}", key=f"question_{i+1}")
114
 
115
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
116
 
117
  # Submit Quiz Button
118
  if st.button("βœ… Submit Quiz"):
119
  if st.session_state.quiz_data:
120
+ correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data)}
121
+ score = sum(1 for q_id, user_ans in st.session_state.user_answers.items() if user_ans == correct_answers.get(q_id, ""))
122
 
123
  st.write("### 🎯 Quiz Results")
124
  st.write(f"Your Score: **{score}/{num_questions}** πŸŽ‰")
125
 
126
+ # Show correct & incorrect answers
127
+ for q_id, user_ans in st.session_state.user_answers.items():
128
+ correct_ans = correct_answers.get(q_id, "")
129
+ if user_ans == correct_ans:
130
+ st.success(f"βœ… {q_id.replace('_', ' ').title()} - Correct! ({correct_ans})")
131
  else:
132
+ st.error(f"❌ {q_id.replace('_', ' ').title()} - Incorrect! Your Answer: {user_ans} | Correct Answer: {correct_ans}")
133
 
134
  # πŸŽ‰ Animations based on score
135
+ time.sleep(1)
136
  if score == num_questions:
137
+ st.snow() # πŸŽ‰ Perfect score effect
138
+ st.success("πŸ† Perfect Score! You're a genius! πŸš€")
139
  elif score / num_questions >= 0.7:
140
+ st.success("πŸŽ‰ Great job! Keep practicing! πŸ’ͺ")
141
  else:
142
  st.warning("πŸ˜ƒ Don't worry! Learn from mistakes and try again! πŸ“š")
143
 
144
  else:
145
  st.error("⚠️ Quiz data not available. Please regenerate the quiz.")