harshith1411 commited on
Commit
508c367
Β·
verified Β·
1 Parent(s): a4a4fca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -48
app.py CHANGED
@@ -4,24 +4,24 @@ 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(
@@ -31,43 +31,36 @@ model = ChatGroq(
31
 
32
  def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
33
  """Generate quiz based on user selection and return JSON data."""
34
- st.info("✨ AI is generating your quiz... Please wait!")
35
- time.sleep(2) # Simulate loading effect
36
-
37
- json_format = {"questions": [{"question": "Sample question?", "options": ["A", "B", "C", "D"], "answer": "A"}]}
38
-
39
- if "MCQ" in quiz_type:
40
- prompt = f"Generate {num_questions} MCQs for a {standard} student on {topic}. Each question should have 4 options and one correct answer. Output JSON format: {json.dumps(json_format)}"
41
- elif "True or False" in quiz_type:
42
- prompt = f"Generate {num_questions} True/False questions for a {standard} student on {topic}. Output JSON format: {json.dumps({'questions': [{'question': 'Sample question?', 'answer': 'True'}]})}"
43
  else: # Fill in the Blanks
44
- prompt = f"Generate {num_questions} Fill-in-the-Blank questions for a {standard} student on {topic}. Output JSON format: {json.dumps({'questions': [{'question': 'Sample question ___?', 'answer': 'correct word'}]})}"
45
 
46
  try:
47
- response = model.predict(prompt).strip().replace("```json", "").replace("```", "")
48
- quiz_data = json.loads(response)
49
- st.balloons() # 🎈 Balloons animation after quiz generation
50
- return quiz_data
51
  except json.JSONDecodeError:
52
- st.error("⚠️ The AI did not return a valid JSON response. Try again!")
53
  return None
54
  except Exception as e:
55
  st.error(f"⚠️ Error: {str(e)}")
56
  return None
57
 
58
  def calculate_score(user_answers, correct_answers):
59
- """Calculate score and return detailed results."""
 
60
  score = 0
61
- detailed_results = []
62
-
63
- for i, (q, ans) in enumerate(user_answers.items()):
64
- correct_ans = correct_answers.get(q, "N/A")
65
- is_correct = ans == correct_ans
66
- detailed_results.append((q, ans, correct_ans, is_correct))
67
  if is_correct:
68
  score += 1
69
 
70
- return score, detailed_results
71
 
72
  # Session state to store quiz data
73
  if 'quiz_data' not in st.session_state:
@@ -82,15 +75,16 @@ if st.button("πŸš€ Generate Quiz"):
82
  if st.session_state.quiz_data:
83
  st.session_state.user_answers = {} # Reset answers
84
  st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
 
85
  else:
86
- st.error("❗ Please enter both the standard and topic.")
87
 
88
  # Display Quiz if Available
89
  if st.session_state.quiz_data:
90
  st.write("### πŸ“ Quiz Questions:")
91
  questions = st.session_state.quiz_data.get("questions", [])
92
 
93
- for i, q in enumerate(questions):
94
  st.write(f"**Q{i+1}: {q['question']}**")
95
 
96
  if quiz_type == "Multiple Choice Questions (MCQ)":
@@ -98,31 +92,35 @@ if st.session_state.quiz_data:
98
  elif quiz_type == "True or False":
99
  user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
100
  else: # Fill in the Blanks
101
- user_answer = st.text_input(f"✍️ Your answer for Question {i+1}", key=f"question_{i+1}")
102
 
103
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
104
 
105
  # Submit Quiz Button
106
- if st.button("Submit Quiz"):
107
  if st.session_state.quiz_data:
108
  correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
109
- score = calculate_score(st.session_state.user_answers, correct_answers)
110
 
111
- st.write("### Quiz Results")
112
- st.write(f"Your Score: {score}/{num_questions} πŸŽ‰")
113
 
114
- # πŸŽ‡ Add Animations Based on Score
 
 
 
 
 
 
 
 
115
  if score == num_questions:
116
- st.balloons() # Full Score: Balloons
117
- st.markdown("πŸ† **Perfect Score! You're an AI Genius!** πŸ†")
118
- elif score >= num_questions * 0.7:
119
- st.snow() # High Score: Snowfall
120
- st.markdown("❄️ **Great Job! Keep Pushing for Perfection!** ❄️")
121
  else:
122
- st.markdown("πŸ”₯ **Don't Worry! Keep Learning and Try Again!** πŸ”₯")
123
 
124
- st.success("Great job! Keep practicing!")
125
  else:
126
- st.error("Quiz data not available. Please regenerate the quiz.")
127
-
128
-
 
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 and Have Fun!')
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(
 
31
 
32
  def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
33
  """Generate quiz based on user selection and return JSON data."""
34
+ if quiz_type == "Multiple Choice Questions (MCQ)":
35
+ 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': '...'}}]}}"
36
+ elif quiz_type == "True or False":
37
+ prompt = f"Generate {num_questions} true or false questions for a {standard} student on {topic}. Return JSON format: {{'questions': [{{'question': '...', 'answer': 'True or False'}}]}}"
 
 
 
 
 
38
  else: # Fill in the Blanks
39
+ 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': '...'}}]}}"
40
 
41
  try:
42
+ response = model.predict(prompt)
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.")
46
  return None
47
  except Exception as e:
48
  st.error(f"⚠️ Error: {str(e)}")
49
  return None
50
 
51
  def calculate_score(user_answers, correct_answers):
52
+ """Calculate score and return details of correct and incorrect answers."""
53
+ results = []
54
  score = 0
55
+
56
+ for q, user_ans in user_answers.items():
57
+ correct_ans = correct_answers.get(q, "")
58
+ is_correct = user_ans == correct_ans
59
+ results.append((q, user_ans, correct_ans, is_correct))
 
60
  if is_correct:
61
  score += 1
62
 
63
+ return score, results
64
 
65
  # Session state to store quiz data
66
  if 'quiz_data' not in st.session_state:
 
75
  if st.session_state.quiz_data:
76
  st.session_state.user_answers = {} # Reset answers
77
  st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
78
+ st.balloons() # 🎈 Balloons for generating the quiz
79
  else:
80
+ st.error("⚠️ Please enter both the standard and topic.")
81
 
82
  # Display Quiz if Available
83
  if st.session_state.quiz_data:
84
  st.write("### πŸ“ Quiz Questions:")
85
  questions = st.session_state.quiz_data.get("questions", [])
86
 
87
+ for i, q in enumerate(questions): # Display all selected questions
88
  st.write(f"**Q{i+1}: {q['question']}**")
89
 
90
  if quiz_type == "Multiple Choice Questions (MCQ)":
 
92
  elif quiz_type == "True or False":
93
  user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
94
  else: # Fill in the Blanks
95
+ user_answer = st.text_input(f"🧐 Your answer for Question {i+1}", key=f"question_{i+1}")
96
 
97
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
98
 
99
  # Submit Quiz Button
100
+ if st.button("βœ… Submit Quiz"):
101
  if st.session_state.quiz_data:
102
  correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
103
+ score, results = calculate_score(st.session_state.user_answers, correct_answers)
104
 
105
+ st.write("### 🎯 Quiz Results")
106
+ st.write(f"Your Score: **{score}/{num_questions}** πŸŽ‰")
107
 
108
+ # Display Correct Answers
109
+ for q_id, user_ans, correct_ans, is_correct in results:
110
+ if is_correct:
111
+ st.success(f"βœ… {q_id.replace('_', ' ').title()} - Correct! ({correct_ans})")
112
+ else:
113
+ st.error(f"❌ {q_id.replace('_', ' ').title()} - Incorrect! Your Answer: {user_ans} | Correct Answer: {correct_ans}")
114
+
115
+ # πŸŽ‰ Animations based on score
116
+ time.sleep(1) # Small delay for better effect
117
  if score == num_questions:
118
+ st.snow() # πŸ† Trophy effect for a perfect score
119
+ st.success("πŸ† Perfect Score! You are a genius! πŸš€")
120
+ elif score / num_questions >= 0.7:
121
+ st.success("πŸŽ‰ Great job! Keep practicing!")
 
122
  else:
123
+ st.warning("πŸ˜ƒ Don't worry! Learn from mistakes and try again!")
124
 
 
125
  else:
126
+ st.error("⚠️ Quiz data not available. Please regenerate the quiz.")