File size: 6,149 Bytes
fdd04ac
 
 
534a28f
fdd04ac
a8e7a5c
36c4dad
fdd04ac
a8e7a5c
a502c90
79dc0e2
a502c90
a8e7a5c
a502c90
508c367
9dddd8f
3d7aaca
 
 
a8e7a5c
508c367
9dddd8f
a8e7a5c
508c367
43c0e4c
a8e7a5c
fdd04ac
 
14e5a2e
a8e7a5c
fdd04ac
 
43c0e4c
3d7aaca
 
 
 
 
 
 
34e467f
 
 
3d7aaca
 
 
 
 
 
 
 
34e467f
 
3d7aaca
 
 
 
 
 
 
 
34e467f
 
3d7aaca
 
 
 
 
 
a8e7a5c
34e467f
3d7aaca
34e467f
43c0e4c
34e467f
3d7aaca
a8e7a5c
9dddd8f
a8e7a5c
 
34e467f
 
 
 
9dddd8f
a8e7a5c
9dddd8f
a8e7a5c
eeab988
 
9dddd8f
a8e7a5c
 
9dddd8f
 
a8e7a5c
 
9dddd8f
 
 
 
 
 
 
 
 
a8e7a5c
79dc0e2
 
 
 
 
a8e7a5c
534a28f
43c0e4c
3d7aaca
79dc0e2
a8e7a5c
3d7aaca
a8e7a5c
fdd04ac
508c367
fdd04ac
a8e7a5c
79dc0e2
a502c90
9dddd8f
 
a8e7a5c
79dc0e2
 
3d7aaca
9dddd8f
3d7aaca
 
a8e7a5c
3d7aaca
79dc0e2
 
36c4dad
a8e7a5c
508c367
79dc0e2
9dddd8f
 
a502c90
79dc0e2
 
 
a8e7a5c
9dddd8f
 
 
 
79dc0e2
9dddd8f
79dc0e2
a8e7a5c
 
79dc0e2
a8e7a5c
9dddd8f
79dc0e2
9dddd8f
79dc0e2
 
 
 
 
9dddd8f
a8e7a5c
34e467f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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.")