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