harshith1411 commited on
Commit
534a28f
Β·
verified Β·
1 Parent(s): eeab988

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -36
app.py CHANGED
@@ -1,26 +1,33 @@
1
  import streamlit as st
2
  from langchain_groq import ChatGroq
3
  import json
 
4
 
5
- # πŸ”Ή Hardcoded Groq API Key (Replace with your actual key)
6
  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(
@@ -28,18 +35,22 @@ model = ChatGroq(
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
  try:
41
  response = model.predict(prompt)
42
- st.write("πŸ”Ή **Raw API Response:**", response) # Debugging
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.")
@@ -48,7 +59,7 @@ def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
48
  st.error(f"⚠️ Error: {str(e)}")
49
  return None
50
 
51
-
52
  def calculate_score(user_answers, correct_answers):
53
  """Calculate score based on user answers."""
54
  return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
@@ -59,41 +70,60 @@ if 'quiz_data' not in st.session_state:
59
  if 'user_answers' not in st.session_state:
60
  st.session_state.user_answers = {}
61
 
62
- # Generate Quiz Button
63
- if st.button("Generate Quiz"):
64
  if standard and topic:
65
- st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
 
66
  if st.session_state.quiz_data:
67
  st.session_state.user_answers = {} # Reset answers
68
- st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
 
69
  else:
70
- st.error("Please enter both the standard and topic.")
71
 
72
  # Display Quiz if Available
73
  if st.session_state.quiz_data:
74
- st.write("### Quiz Questions:")
75
  questions = st.session_state.quiz_data.get("questions", [])
76
 
77
  for i, q in enumerate(questions): # Display all selected questions
78
  st.write(f"**Q{i+1}: {q['question']}**")
79
 
80
- if quiz_type == "Multiple Choice Questions (MCQ)":
81
- user_answer = st.radio(f"Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
82
- elif quiz_type == "True or False":
83
- user_answer = st.radio(f"Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
84
  else: # Fill in the Blanks
85
- user_answer = st.text_input(f"Your answer for Question {i+1}", key=f"question_{i+1}")
86
 
87
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
88
 
89
- # Submit Quiz Button
90
- if st.button("Submit Quiz"):
91
  if st.session_state.quiz_data:
92
  correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
93
  score = calculate_score(st.session_state.user_answers, correct_answers)
94
 
95
- st.write("### Quiz Results")
96
- st.write(f"Your Score: {score}/{num_questions} πŸŽ‰")
97
- st.success("Great job! Keep practicing!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  else:
99
- st.error("Quiz data not available. Please regenerate the quiz.")
 
1
  import streamlit as st
2
  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(
 
35
  groq_api_key=GROQ_API_KEY
36
  )
37
 
38
+ # Function to Generate Quiz
39
  def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
40
  """Generate quiz based on user selection and return JSON data."""
41
+ st.info("✨ AI is generating your quiz... Please wait!") # Show animated loading message
42
+
43
+ time.sleep(1) # Simulate loading effect
44
+
45
+ if "MCQ" in quiz_type:
46
  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': '...'}}]}}"
47
+ elif "True or False" in quiz_type:
48
  prompt = f"Generate {num_questions} true or false questions for a {standard} student on {topic}. Return JSON format: {{'questions': [{{'question': '...', 'answer': 'True or False'}}]}}"
49
  else: # Fill in the Blanks
50
  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': '...'}}]}}"
51
 
52
  try:
53
  response = model.predict(prompt)
 
54
  return json.loads(response) # Parse JSON response safely
55
  except json.JSONDecodeError:
56
  st.error("⚠️ Failed to generate quiz. The AI did not return a proper JSON response.")
 
59
  st.error(f"⚠️ Error: {str(e)}")
60
  return None
61
 
62
+ # Function to Calculate Score
63
  def calculate_score(user_answers, correct_answers):
64
  """Calculate score based on user answers."""
65
  return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
 
70
  if 'user_answers' not in st.session_state:
71
  st.session_state.user_answers = {}
72
 
73
+ # Generate Quiz Button with Animation
74
+ if st.button("πŸš€ Generate Quiz"):
75
  if standard and topic:
76
+ with st.spinner("πŸ”„ AI is thinking... Generating your quiz!"):
77
+ st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
78
  if st.session_state.quiz_data:
79
  st.session_state.user_answers = {} # Reset answers
80
+ st.success(f"πŸŽ‰ {quiz_type} Quiz with {num_questions} Questions Generated Successfully!")
81
+ st.balloons()
82
  else:
83
+ st.error("⚠️ Please enter both the Standard and Topic.")
84
 
85
  # Display Quiz if Available
86
  if st.session_state.quiz_data:
87
+ st.markdown("<h3 style='color: #2ECC71;'>πŸ“ Your Quiz Questions:</h3>", unsafe_allow_html=True)
88
  questions = st.session_state.quiz_data.get("questions", [])
89
 
90
  for i, q in enumerate(questions): # Display all selected questions
91
  st.write(f"**Q{i+1}: {q['question']}**")
92
 
93
+ if "MCQ" in quiz_type:
94
+ user_answer = st.radio(f"🎯 Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
95
+ elif "True or False" in quiz_type:
96
+ user_answer = st.radio(f"βœ… Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
97
  else: # Fill in the Blanks
98
+ user_answer = st.text_input(f"✏️ Your answer for Question {i+1}", key=f"question_{i+1}")
99
 
100
  st.session_state.user_answers[f"question_{i+1}"] = user_answer
101
 
102
+ # Submit Quiz Button with Animated Score Display
103
+ if st.button("πŸ“Š Submit Quiz"):
104
  if st.session_state.quiz_data:
105
  correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
106
  score = calculate_score(st.session_state.user_answers, correct_answers)
107
 
108
+ # Animated Progress Bar
109
+ st.markdown("<h3 style='color: #F39C12;'>⏳ Calculating Score...</h3>", unsafe_allow_html=True)
110
+ progress_bar = st.progress(0)
111
+ for percent_complete in range(100):
112
+ time.sleep(0.01)
113
+ progress_bar.progress(percent_complete + 1)
114
+
115
+ # Score Results
116
+ st.markdown("<h2 style='color: #8E44AD;'>πŸ“Š Your Quiz Results</h2>", unsafe_allow_html=True)
117
+ st.write(f"βœ… **Your Score: {score}/{num_questions} πŸŽ‰**")
118
+
119
+ # Show different messages based on score
120
+ if score == num_questions:
121
+ st.success("🌟 Perfect Score! You're a genius! πŸš€")
122
+ st.balloons()
123
+ elif score >= num_questions / 2:
124
+ st.info("πŸ’‘ Great job! Keep practicing to improve! πŸ’ͺ")
125
+ else:
126
+ st.warning("πŸ“š Don't worry! Try again and improve your score! 😊")
127
+
128
  else:
129
+ st.error("⚠️ Quiz data not available. Please regenerate the quiz.")