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!') # User Inputs standard = st.text_input('📚 Enter Standard/Grade') topic = st.text_input('📝 Enter Topic') quiz_type = st.selectbox("🎭 Select Quiz Type", ["Multiple Choice Questions (MCQ)", "True or False", "Fill in the Blanks"]) difficulty = st.radio("📊 Select Difficulty Level", ["Low", "Medium", "Hard"]) 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 questions dynamically based on user selection.""" 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 exactly 4 options (A, B, C, D) and one correct answer. Return the result in this format: 1. Question text? A) Option 1 B) Option 2 C) Option 3 D) Option 4 Answer: Correct Option (A, B, C, or D) """ elif quiz_type == "True or False": prompt = f""" Generate {num_questions} True or False questions for a {standard} student on {topic}. Return the result in this format: 1. Question text? 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}. Return the result in this format: 1. The capital of France is __. Answer: Paris """ try: response = model.predict(prompt).strip() # Ensure clean output quiz_lines = response.split("\n") # Split response into lines questions = [] current_question = None for line in quiz_lines: if line.strip() and not line.startswith("Answer:"): if line[0].isdigit(): # New question detected if current_question: questions.append(current_question) current_question = {"question": line, "options": [], "answer": ""} elif line[0] in "ABCD)" and quiz_type == "Multiple Choice Questions (MCQ)": current_question["options"].append(line) elif line.startswith("Answer:"): current_question["answer"] = line.split("Answer: ")[1] if current_question: questions.append(current_question) return questions except Exception as e: st.error(f"⚠️ Failed to generate quiz. Error: {str(e)}") return None # 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! 🎉") else: st.error("⚠️ Please enter both the standard and topic.") # Display Quiz if Available if st.session_state.quiz_data: st.write("### 📝 Quiz Questions:") for i, q in enumerate(st.session_state.quiz_data): st.write(f"**Q{i+1}: {q['question']}**") if quiz_type == "Multiple Choice Questions (MCQ)": user_answer = st.radio(f"🧐 Select your answer for Q{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 Q{i+1}", options=["True", "False"], key=f"question_{i+1}") else: # Fill in the Blanks user_answer = st.text_input(f"🧐 Your answer for Q{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"].strip().lower() for i, q in enumerate(st.session_state.quiz_data)} score = sum(1 for q_id, user_ans in st.session_state.user_answers.items() if user_ans.strip().lower() == correct_answers.get(q_id, "")) st.write("### 🎯 Quiz Results") st.write(f"Your Score: **{score}/{num_questions}** 🎉") # Show correct & incorrect answers for q_id, user_ans in st.session_state.user_answers.items(): correct_ans = correct_answers.get(q_id, "") if user_ans == correct_ans: 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) if score == num_questions: st.snow() # 🎉 Perfect score effect st.success("🏆 Perfect Score! You're 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.")