File size: 4,264 Bytes
0d405b4
 
 
 
 
 
4126038
 
 
0d405b4
 
ad090e6
0d405b4
 
 
 
ad090e6
 
0d405b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4126038
0d405b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac2cf39
0d405b4
 
 
 
 
 
 
ad090e6
c7d42ba
 
07fafa2
 
 
 
 
 
 
 
 
c7d42ba
 
 
ad090e6
0d405b4
 
 
ad090e6
 
0d405b4
 
ad090e6
0d405b4
73a7277
1e0d77b
0d405b4
 
 
 
 
 
 
 
 
 
 
 
 
 
ad090e6
 
 
 
 
 
 
 
 
 
 
 
0d405b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_google_genai import ChatGoogleGenerativeAI
import fitz
import json
import docx
import os


# Title
st.title("πŸ“„ File-based MCQ Generator")

# Sidebar
st.sidebar.title("Upload & Settings")

# Upload file
uploaded_file = st.sidebar.file_uploader("Upload a file (PDF or Word)", type=["pdf", "docx"])

# Number of questions
number_of_questions = st.sidebar.slider("Number of questions", min_value=1, max_value=20, value=5)

# Session states
if "mcqs" not in st.session_state:
    st.session_state.mcqs = []
if "current_q" not in st.session_state:
    st.session_state.current_q = 0
if "user_answers" not in st.session_state:
    st.session_state.user_answers = {}
if "quiz_finished" not in st.session_state:
    st.session_state.quiz_finished = False

# Gemini setup
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
llm = ChatGoogleGenerativeAI(
    model="gemini-2.0-flash",
    google_api_key=GOOGLE_API_KEY,
    temperature=0.7
)

template = """
You are an expert MCQ generator. Generate {number} unique multiple-choice questions from the given text.
Each question must have exactly 1 correct answer and 3 incorrect options.
Strictly return output in the following JSON format (no explanations, no markdown):

[
  {{
    "question": "What is ...?",
    "options": ["Option A", "Option B", "Option C", "Option D"],
    "answer": "Option D"
  }},
  ...
]

TEXT:
{text}
"""


prompt = PromptTemplate(
    input_variables=["text", "number"],
    template=template
)

mcq_chain = LLMChain(llm=llm, prompt=prompt)

# Extract text from PDF or Word
def extract_text(file):
    if file.name.endswith(".pdf"):
        # Read the entire file content into memory
        file_bytes = file.read()
        # Open the PDF from the byte stream
        doc = fitz.open(stream=file_bytes, filetype="pdf")
        # Extract text from all pages
        text = ""
        for page in doc:
            text += page.get_text()
        return text
    elif file.name.endswith(".docx"):
        doc = docx.Document(file)
        return "\n".join([para.text for para in doc.paragraphs])
    return ""

# Generate MCQs
if st.sidebar.button("Generate MCQs"):
    if uploaded_file is None:
        st.error("Please upload a file.")
    else:
        with st.spinner("Extracting text and generating MCQs..."):
            text = extract_text(uploaded_file)
            try:
                response = mcq_chain.run(text=text, number=str(number_of_questions))
                mcqs_json = json.loads(response[8:-3])
                st.session_state.mcqs = mcqs_json
                st.session_state.current_q = 0
                st.session_state.user_answers = {}
                st.session_state.quiz_finished = False
                st.success("βœ… MCQs generated successfully!")
            except Exception as e:
                st.error(f"Error generating MCQs: {e}")

# Display question
if st.session_state.mcqs and not st.session_state.quiz_finished:
    idx = st.session_state.current_q
    q_data = st.session_state.mcqs[idx]

    st.subheader(f"Question {idx + 1}: {q_data['question']}")
    
    with st.form(key=f"form_{idx}"):
        selected_option = st.radio("Choose an answer:", q_data["options"], key=f"radio_{idx}")
        submitted = st.form_submit_button("Next")

        if submitted:
            st.session_state.user_answers[idx] = selected_option
            if idx < len(st.session_state.mcqs) - 1:
                st.session_state.current_q += 1
            else:
                st.session_state.quiz_finished = True
                st.success("πŸŽ‰ Quiz completed!")

# Show result
if st.session_state.quiz_finished:
    st.header("πŸ“Š Quiz Results")
    score = 0
    total = len(st.session_state.mcqs)

    for i, q in enumerate(st.session_state.mcqs):
        user_ans = st.session_state.user_answers.get(i)
        correct_ans = q["answer"]
        if user_ans == correct_ans:
            score += 1
        st.markdown(f"**Q{i+1}: {q['question']}**")
        st.markdown(f"- Your answer: {user_ans}")
        st.markdown(f"- Correct answer: {correct_ans}")
        st.markdown("---")

    st.success(f"βœ… You scored {score} out of {total}")