harshith1411's picture
Update app.py
14e5a2e verified
raw
history blame
5.66 kB
import streamlit as st
from langchain_groq import ChatGroq
import json
import time
# πŸ”Ή Groq API Key (Replace with your actual key)
GROQ_API_KEY = "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"
# Streamlit App Title
st.title('🎯 AI Quiz Generator')
st.subheader('πŸš€ Test Your Knowledge and Have Fun!')
# Input Fields
standard = st.text_input('πŸ“š Enter Standard/Grade')
topic = st.text_input('πŸ“ Enter Topic')
# Quiz Type Selection
quiz_type = st.selectbox("🎭 Select Quiz Type", ["Multiple Choice Questions (MCQ)", "True or False", "Fill in the Blanks"])
# Difficulty Level Selection
difficulty = st.radio("πŸ“Š Select Difficulty Level", ["Low", "Medium", "Hard"])
# Number of Questions Selection (1 to 10)
num_questions = st.slider("πŸ”’ Select Number of Questions", min_value=1, max_value=10, value=5)
# Initialize AI Model
model = ChatGroq(
temperature=0.6,
groq_api_key=GROQ_API_KEY,
model_name="llama-3.3-70b-versatile"
)
def generate_quiz(standard, topic, quiz_type, difficulty, num_questions):
"""Generate quiz based on user selection and return JSON data."""
if quiz_type == "Multiple Choice Questions (MCQ)":
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': '...'}}]}}"
elif quiz_type == "True or False":
prompt = f"Generate {num_questions} true or false questions for a {standard} student on {topic}. Return JSON format: {{'questions': [{{'question': '...', 'answer': 'True or False'}}]}}"
else: # Fill in the Blanks
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': '...'}}]}}"
try:
response = model.predict(prompt)
return json.loads(response) # Parse JSON response safely
except json.JSONDecodeError:
st.error("⚠️ Failed to generate quiz. The AI did not return a proper JSON response.")
return None
except Exception as e:
st.error(f"⚠️ Error: {str(e)}")
return None
def calculate_score(user_answers, correct_answers):
"""Calculate score and return details of correct and incorrect answers."""
results = []
score = 0
for q, user_ans in user_answers.items():
correct_ans = correct_answers.get(q, "")
is_correct = user_ans == correct_ans
results.append((q, user_ans, correct_ans, is_correct))
if is_correct:
score += 1
return score, results
# Session state to store quiz data
if 'quiz_data' not in st.session_state:
st.session_state.quiz_data = None
if 'user_answers' not in st.session_state:
st.session_state.user_answers = {}
# Generate Quiz Button
if st.button("πŸš€ Generate Quiz"):
if standard and topic:
st.session_state.quiz_data = generate_quiz(standard, topic, quiz_type, difficulty, num_questions)
if st.session_state.quiz_data:
st.session_state.user_answers = {} # Reset answers
st.success(f"{quiz_type} Quiz Generated with {num_questions} Questions!")
st.balloons() # 🎈 Balloons for generating the quiz
else:
st.error("⚠️ Please enter both the standard and topic.")
# Display Quiz if Available
if st.session_state.quiz_data:
st.write("### πŸ“ Quiz Questions:")
questions = st.session_state.quiz_data.get("questions", [])
for i, q in enumerate(questions): # Display all selected questions
st.write(f"**Q{i+1}: {q['question']}**")
if quiz_type == "Multiple Choice Questions (MCQ)":
user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=q["options"], key=f"question_{i+1}")
elif quiz_type == "True or False":
user_answer = st.radio(f"🧐 Select your answer for Question {i+1}", options=["True", "False"], key=f"question_{i+1}")
else: # Fill in the Blanks
user_answer = st.text_input(f"🧐 Your answer for Question {i+1}", key=f"question_{i+1}")
st.session_state.user_answers[f"question_{i+1}"] = user_answer
# Submit Quiz Button
if st.button("βœ… Submit Quiz"):
if st.session_state.quiz_data:
correct_answers = {f"question_{i+1}": q["answer"] for i, q in enumerate(st.session_state.quiz_data["questions"])}
score, results = calculate_score(st.session_state.user_answers, correct_answers)
st.write("### 🎯 Quiz Results")
st.write(f"Your Score: **{score}/{num_questions}** πŸŽ‰")
# Display Correct Answers
for q_id, user_ans, correct_ans, is_correct in results:
if is_correct:
st.success(f"βœ… {q_id.replace('_', ' ').title()} - Correct! ({correct_ans})")
else:
st.error(f"❌ {q_id.replace('_', ' ').title()} - Incorrect! Your Answer: {user_ans} | Correct Answer: {correct_ans}")
# πŸŽ‰ Animations based on score
time.sleep(1) # Small delay for better effect
if score == num_questions:
st.snow() # πŸ† Trophy effect for a perfect score
st.success("πŸ† Perfect Score! You are a genius! πŸš€")
elif score / num_questions >= 0.7:
st.success("πŸŽ‰ Great job! Keep practicing!")
else:
st.warning("πŸ˜ƒ Don't worry! Learn from mistakes and try again!")
else:
st.error("⚠️ Quiz data not available. Please regenerate the quiz.")