harshith1411 commited on
Commit
a502c90
Β·
verified Β·
1 Parent(s): 2c9296d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -63
app.py CHANGED
@@ -3,31 +3,25 @@ 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(
@@ -39,14 +33,10 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
39
  """Generate quiz based on user selection and return JSON data."""
40
  st.info("✨ AI is generating your quiz... Please wait!")
41
 
42
- time.sleep(1) # Simulate loading effect
43
 
44
  # Define structured JSON format instruction
45
- json_format = {
46
- "questions": [
47
- {"question": "Sample question?", "options": ["A", "B", "C", "D"], "answer": "A"}
48
- ]
49
- }
50
 
51
  if "MCQ" in quiz_type:
52
  prompt = f"""
@@ -68,7 +58,10 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
68
  try:
69
  response = model.predict(prompt) # AI Response
70
  response = response.strip().replace("```json", "").replace("```", "") # Remove formatting if needed
71
- return json.loads(response) # Parse JSON safely
 
 
 
72
  except json.JSONDecodeError:
73
  st.error("⚠️ The AI did not return a valid JSON response. Try again!")
74
  return None
@@ -76,9 +69,6 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
76
  st.error(f"⚠️ Error: {str(e)}")
77
  return None
78
 
79
-
80
-
81
- # Function to Calculate Score
82
  def calculate_score(user_answers, correct_answers):
83
  """Calculate score based on user answers."""
84
  return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
@@ -89,60 +79,49 @@ if 'quiz_data' not in st.session_state:
89
  if 'user_answers' not in st.session_state:
90
  st.session_state.user_answers = {}
91
 
92
- # Generate Quiz Button with Animation
93
  if st.button("πŸš€ Generate Quiz"):
94
  if standard and topic:
95
- with st.spinner("πŸ”„ AI is thinking... Generating your quiz!"):
96
- st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
97
  if st.session_state.quiz_data:
98
  st.session_state.user_answers = {} # Reset answers
99
- st.success(f"πŸŽ‰ {quiz_type} Quiz with {num_questions} Questions Generated Successfully!")
100
- st.balloons()
101
  else:
102
- st.error("⚠️ Please enter both the Standard and Topic.")
103
 
104
  # Display Quiz if Available
105
  if st.session_state.quiz_data:
106
- st.markdown("<h3 style='color: #2ECC71;'>πŸ“ Your Quiz Questions:</h3>", unsafe_allow_html=True)
107
  questions = st.session_state.quiz_data.get("questions", [])
108
 
109
  for i, q in enumerate(questions): # Display all selected questions
110
  st.write(f"**Q{i+1}: {q['question']}**")
111
 
112
- if "MCQ" in quiz_type:
113
- user_answer = st.radio(f"🎯 Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
114
- elif "True or False" in quiz_type:
115
- user_answer = st.radio(f"βœ… Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
116
  else: # Fill in the Blanks
117
- user_answer = st.text_input(f"✏️ Your answer for Question {i+1}", key=f"question_{i+1}")
118
 
119
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
120
 
121
- # Submit Quiz Button with Animated Score Display
122
- if st.button("πŸ“Š Submit Quiz"):
123
  if st.session_state.quiz_data:
124
  correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
125
  score = calculate_score(st.session_state.user_answers, correct_answers)
126
 
127
- # Animated Progress Bar
128
- st.markdown("<h3 style='color: #F39C12;'>⏳ Calculating Score...</h3>", unsafe_allow_html=True)
129
- progress_bar = st.progress(0)
130
- for percent_complete in range(100):
131
- time.sleep(0.01)
132
- progress_bar.progress(percent_complete + 1)
133
-
134
- # Score Results
135
- st.markdown("<h2 style='color: #8E44AD;'>πŸ“Š Your Quiz Results</h2>", unsafe_allow_html=True)
136
- st.write(f"βœ… **Your Score: {score}/{num_questions} πŸŽ‰**")
137
-
138
- # Show different messages based on score
139
  if score == num_questions:
140
- st.success("🌟 Perfect Score! You're a genius! πŸš€")
141
- st.balloons()
142
- elif score >= num_questions / 2:
143
- st.info("πŸ’‘ Great job! Keep practicing to improve! πŸ’ͺ")
144
  else:
145
- st.warning("πŸ“š Don't worry! Try again and improve your score! 😊")
146
 
 
147
  else:
148
- st.error("⚠️ Quiz data not available. Please regenerate the quiz.")
 
3
  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(
 
33
  """Generate quiz based on user selection and return JSON data."""
34
  st.info("✨ AI is generating your quiz... Please wait!")
35
 
36
+ time.sleep(2) # Simulate loading effect
37
 
38
  # Define structured JSON format instruction
39
+ json_format = {"questions": [{"question": "Sample question?", "options": ["A", "B", "C", "D"], "answer": "A"}]}
 
 
 
 
40
 
41
  if "MCQ" in quiz_type:
42
  prompt = f"""
 
58
  try:
59
  response = model.predict(prompt) # AI Response
60
  response = response.strip().replace("```json", "").replace("```", "") # Remove formatting if needed
61
+ quiz_data = json.loads(response) # Parse JSON safely
62
+
63
+ st.balloons() # 🎈 Balloons animation after quiz generation
64
+ return quiz_data
65
  except json.JSONDecodeError:
66
  st.error("⚠️ The AI did not return a valid JSON response. Try again!")
67
  return None
 
69
  st.error(f"⚠️ Error: {str(e)}")
70
  return None
71
 
 
 
 
72
  def calculate_score(user_answers, correct_answers):
73
  """Calculate score based on user answers."""
74
  return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
 
79
  if 'user_answers' not in st.session_state:
80
  st.session_state.user_answers = {}
81
 
82
+ # Generate Quiz Button
83
  if st.button("πŸš€ Generate Quiz"):
84
  if standard and topic:
85
+ st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
 
86
  if st.session_state.quiz_data:
87
  st.session_state.user_answers = {} # Reset answers
88
+ st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
 
89
  else:
90
+ st.error("❗ Please enter both the standard and topic.")
91
 
92
  # Display Quiz if Available
93
  if st.session_state.quiz_data:
94
+ st.write("### πŸ“ Quiz Questions:")
95
  questions = st.session_state.quiz_data.get("questions", [])
96
 
97
  for i, q in enumerate(questions): # Display all selected questions
98
  st.write(f"**Q{i+1}: {q['question']}**")
99
 
100
+ if quiz_type == "Multiple Choice Questions (MCQ)":
101
+ user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
102
+ elif quiz_type == "True or False":
103
+ user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
104
  else: # Fill in the Blanks
105
+ user_answer = st.text_input(f"✍️ Your answer for Question {i+1}", key=f"question_{i+1}")
106
 
107
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
108
 
109
+ # Submit Quiz Button
110
+ if st.button("🏁 Submit Quiz"):
111
  if st.session_state.quiz_data:
112
  correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
113
  score = calculate_score(st.session_state.user_answers, correct_answers)
114
 
115
+ st.write("### πŸ† Quiz Results")
116
+ st.write(f"πŸŽ‰ Your Score: **{score}/{num_questions}**")
117
+
 
 
 
 
 
 
 
 
 
118
  if score == num_questions:
119
+ st.success("πŸ₯‡ Perfect Score! You're a genius! πŸŽ–οΈ")
120
+ elif score >= num_questions // 2:
121
+ st.success("πŸ‘ Well done! Keep learning! πŸ“š")
 
122
  else:
123
+ st.warning("πŸ” Try again! You can improve! πŸ’‘")
124
 
125
+ st.snow() # πŸ† Trophy animation after quiz submission
126
  else:
127
+ st.error("🚨 Quiz data not available. Please regenerate the quiz.")