harshith1411 commited on
Commit
43c0e4c
Β·
verified Β·
1 Parent(s): 405f86f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -79
app.py CHANGED
@@ -2,114 +2,93 @@ import streamlit as st
2
  from langchain_groq import ChatGroq
3
  import json
4
 
5
- # App Configuration
6
- st.set_page_config(page_title="AI Quiz Generator", layout="centered")
7
 
8
- # Title and UI
9
- st.title("πŸ“š AI Quiz Generator")
10
- st.subheader("πŸš€ Test Your Knowledge!")
11
 
12
- # User Input
13
- A = st.text_input("πŸ“– Enter Standard")
14
- B = st.text_input("🧠 Enter a Topic")
15
 
16
- # Initialize ChatGroq Model (Replace with actual API key)
 
 
 
 
 
 
 
 
 
17
  model = ChatGroq(
18
  temperature=0.6,
19
- groq_api_key="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"
20
  )
21
 
22
- def generate_quiz(standard, topic, difficulty):
23
- """
24
- Generates a quiz with 5 multiple-choice questions.
25
- Returns structured JSON output.
26
- """
27
- prompt = (
28
- f"Generate a quiz with exactly 5 multiple choice questions for a {standard} student on the topic of {topic}. "
29
- "Each question should have four options and one correct answer. "
30
- "Return the output in JSON format with the following structure: "
31
- "{ \"questions\": [ {\"question\": \"...\", \"options\": [\"...\", \"...\", \"...\", \"...\"], \"answer\": \"...\"} ] }"
32
- )
33
  response = model.predict(prompt)
34
  try:
35
- return json.loads(response)
36
  except json.JSONDecodeError:
37
- st.error("⚠️ Failed to generate quiz. Please try again.")
38
  return None
39
 
40
  def calculate_score(user_answers, correct_answers):
41
- """Calculate the score based on user responses."""
42
  return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
43
 
44
- # Session state for quiz management
45
- if "quiz_data" not in st.session_state:
46
  st.session_state.quiz_data = None
47
- if "user_answers" not in st.session_state:
48
  st.session_state.user_answers = {}
49
- if "quiz_submitted" not in st.session_state:
50
- st.session_state.quiz_submitted = False
51
-
52
- # Difficulty Selection
53
- difficulty = st.radio("🎯 Select Difficulty Level", ["Low", "Medium", "Hard"])
54
 
55
  # Generate Quiz Button
56
- if st.button("✨ Generate Quiz"):
57
- if A and B:
58
- st.session_state.quiz_data = generate_quiz(A, B, difficulty)
59
  if st.session_state.quiz_data:
60
- st.session_state.user_answers = {} # Reset user answers
61
- st.session_state.quiz_submitted = False
62
- st.success("βœ… Quiz Generated! Scroll down to answer the questions.")
63
  else:
64
- st.error("⚠️ Please enter both the standard and topic.")
65
 
66
  # Display Quiz if Available
67
  if st.session_state.quiz_data:
68
- st.write("## πŸ“ Quiz Questions")
69
  questions = st.session_state.quiz_data.get("questions", [])
70
 
71
- for i, q in enumerate(questions[:5]): # Limit to 5 questions
72
- with st.expander(f"**Q{i+1}: {q['question']}**"):
73
- user_answer = st.radio(
74
- "Select your answer:",
75
- options=q["options"],
76
- key=f"question_{i+1}"
77
- )
78
- st.session_state.user_answers[f"question_{i+1}"] = user_answer
 
 
 
79
 
80
  # Submit Quiz Button
81
- if st.button("πŸ“€ Submit Quiz"):
82
  if st.session_state.quiz_data:
83
- correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"][:5])}
84
  score = calculate_score(st.session_state.user_answers, correct_answers)
85
 
86
- st.session_state.quiz_submitted = True
87
- st.session_state.score = score
88
-
89
- # Display Results After Submission
90
- if st.session_state.quiz_submitted:
91
- st.write("## 🎯 Quiz Results")
92
-
93
- # Display correct and user answers side by side
94
- col1, col2 = st.columns(2)
95
- with col1:
96
- st.write("### βœ… Correct Answers")
97
- for i, q in enumerate(st.session_state.quiz_data["questions"][:5]):
98
- st.write(f"**Q{i+1}:** {q['answer']}")
99
-
100
- with col2:
101
- st.write("### πŸ“ Your Answers")
102
- for i, ans in st.session_state.user_answers.items():
103
- st.write(f"**{i.replace('_', ' ').title()}:** {ans}")
104
-
105
- # Final Score Display
106
- st.markdown(f"## πŸŽ‰ Your Score: **{st.session_state.score}/5**")
107
-
108
- # Feedback Message
109
- if st.session_state.score == 5:
110
- st.success("πŸ”₯ Perfect! You're a genius!")
111
- elif st.session_state.score >= 3:
112
- st.info("πŸ‘ Great job! Keep practicing.")
113
  else:
114
- st.warning("πŸ“š Keep learning! Try again.")
115
-
 
2
  from langchain_groq import ChatGroq
3
  import json
4
 
5
+ # Securely Load API Key (Replace with your actual key if not using secrets)
6
+ GROQ_API_KEY = st.secrets.get("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(
27
  temperature=0.6,
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
  response = model.predict(prompt)
41
  try:
42
+ return json.loads(response) # Parse JSON response safely
43
  except json.JSONDecodeError:
44
+ st.error("Failed to generate quiz. Try again.")
45
  return None
46
 
47
  def calculate_score(user_answers, correct_answers):
48
+ """Calculate score based on user answers."""
49
  return sum(1 for q, ans in user_answers.items() if correct_answers.get(q) == ans)
50
 
51
+ # Session state to store quiz data
52
+ if 'quiz_data' not in st.session_state:
53
  st.session_state.quiz_data = None
54
+ if 'user_answers' not in st.session_state:
55
  st.session_state.user_answers = {}
 
 
 
 
 
56
 
57
  # Generate Quiz Button
58
+ if st.button("Generate Quiz"):
59
+ if standard and topic:
60
+ st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
61
  if st.session_state.quiz_data:
62
+ st.session_state.user_answers = {} # Reset answers
63
+ st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
 
64
  else:
65
+ st.error("Please enter both the standard and topic.")
66
 
67
  # Display Quiz if Available
68
  if st.session_state.quiz_data:
69
+ st.write("### Quiz Questions:")
70
  questions = st.session_state.quiz_data.get("questions", [])
71
 
72
+ for i, q in enumerate(questions): # Display all selected questions
73
+ st.write(f"**Q{i+1}: {q['question']}**")
74
+
75
+ if quiz_type == "Multiple Choice Questions (MCQ)":
76
+ user_answer = st.radio(f"Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
77
+ elif quiz_type == "True or False":
78
+ user_answer = st.radio(f"Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
79
+ else: # Fill in the Blanks
80
+ user_answer = st.text_input(f"Your answer for Question {i+1}", key=f"question_{i+1}")
81
+
82
+ st.session_state.user_answers[f"question_{i+1}"] = user_answer
83
 
84
  # Submit Quiz Button
85
+ if st.button("Submit Quiz"):
86
  if st.session_state.quiz_data:
87
+ correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
88
  score = calculate_score(st.session_state.user_answers, correct_answers)
89
 
90
+ st.write("### Quiz Results")
91
+ st.write(f"Your Score: {score}/{num_questions} πŸŽ‰")
92
+ st.success("Great job! Keep practicing!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  else:
94
+ st.error("Quiz data not available. Please regenerate the quiz.")