import streamlit as st from langchain_groq import ChatGroq import json import time # 🎯 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') # 🔹 User Selects Quiz Type quiz_type = st.radio("🎭 Select Quiz Type", ["MCQ", "True/False", "Fill in the Blanks"]) # 🔹 Difficulty Level difficulty = st.radio("📊 Select Difficulty Level", ["Low", "Medium", "Hard"]) # 🔹 Number of Questions (1-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 topic-specific quiz using AI in JSON format.""" format_example = { "MCQ": ''' { "questions": [ { "question": "What is the capital of France?", "options": ["A) Berlin", "B) Madrid", "C) Paris", "D) Rome"], "answer": "C) Paris" } ] } ''', "True/False": ''' { "questions": [ { "question": "The Sun is a star.", "answer": "True" } ] } ''', "Fill in the Blanks": ''' { "questions": [ { "question": "The powerhouse of the cell is the ____.", "answer": "Mitochondria" } ] } ''' } prompt = f""" You are a quiz generator bot. Generate a {quiz_type} quiz with {num_questions} questions for a {standard} grade student on the topic '{topic}' with {difficulty} difficulty. Strictly return the response in JSON format. Format Example: {format_example[quiz_type]} """ try: response = model.predict(prompt).strip() json_start = response.find('{') json_end = response.rfind('}') if json_start != -1 and json_end != -1: response = response[json_start:json_end+1] # Extract valid JSON quiz_data = json.loads(response) return quiz_data if "questions" in quiz_data else None except json.JSONDecodeError: st.error("⚠️ AI response is not valid JSON. Try again!") return None def normalize_answer(answer): """Standardize answers for case-insensitive comparison.""" return answer.strip().lower() def calculate_score(user_answers, correct_answers): """Calculate quiz score and return result details.""" results, score = [], 0 for q, user_ans in user_answers.items(): correct_ans = normalize_answer(correct_answers.get(q, "")) user_ans = normalize_answer(user_ans) is_correct = user_ans == correct_ans results.append((q, user_ans, correct_ans, is_correct)) if is_correct: score += 1 return score, results # 🔹 Store Quiz Data in Session 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 = {} st.success(f"✅ {quiz_type} Quiz Generated on '{topic}' with {num_questions} Questions!") st.balloons() 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): st.write(f"**Q{i+1}: {q['question']}**") if quiz_type == "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/False": user_answer = st.radio(f"🧐 Select True or False for Question {i+1}", options=["True", "False"], key=f"question_{i+1}") else: user_answer = st.text_input(f"🧐 Fill in the blank 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"].strip().lower() 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}** 🎉") # 🔹 Show Correct/Incorrect Answers for q_id, user_ans, correct_ans, is_correct in results: question_num = q_id.replace("question_", "Question ") if is_correct: st.success(f"✅ {question_num} - Correct! ({correct_ans.upper()})") else: st.error(f"❌ {question_num} - Incorrect! Your Answer: {user_ans.upper()} | Correct Answer: {correct_ans.upper()}") # 🔹 Animations Based on Score time.sleep(1) if score == num_questions: st.snow() 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.")