Spaces:
Sleeping
Sleeping
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.") | |