harshith1411 commited on
Commit
a8e7a5c
Β·
verified Β·
1 Parent(s): 9dddd8f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -84
app.py CHANGED
@@ -3,144 +3,114 @@ from langchain_groq import ChatGroq
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
- # 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": "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
- try:
69
- response = model.predict(prompt).strip() # Ensure clean output
 
 
 
70
 
71
- # Validate if response is in JSON format
 
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("⚠️ Failed to generate quiz. The AI did not return a proper JSON response.")
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
- """Convert answers to a standard format for comparison."""
88
- answer = answer.strip().lower()
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 of correct and incorrect answers."""
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
- # Session state to store quiz data
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
- st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
 
119
  if st.session_state.quiz_data:
120
- st.session_state.user_answers = {} # Reset answers
121
- st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions! πŸŽ‰")
122
- st.balloons() # 🎈 Balloons for generating the quiz
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): # Display all selected questions
132
  st.write(f"**Q{i+1}: {q['question']}**")
133
 
134
- if quiz_type == "Multiple Choice Questions (MCQ)":
135
  user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
136
- elif quiz_type == "True or False":
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
- # Display Correct Answers
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
- # πŸŽ‰ Animations based on score
161
- time.sleep(1) # Small delay for better effect
162
  if score == num_questions:
163
- st.snow() # πŸ† Trophy effect for a perfect score
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
+