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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import PyPDF2
|
4 |
+
import docx
|
5 |
+
import googleapiclient.discovery
|
6 |
+
import nltk
|
7 |
+
from nltk.tokenize import sent_tokenize
|
8 |
+
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer
|
9 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
10 |
+
import streamlit as st
|
11 |
+
import pandas as pd
|
12 |
+
import random
|
13 |
+
from io import StringIO
|
14 |
+
import logging
|
15 |
+
|
16 |
+
# Setup logging
|
17 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
18 |
+
logger = logging.getLogger(__name__)
|
19 |
+
|
20 |
+
# Download necessary NLTK resources
|
21 |
+
nltk.download('punkt')
|
22 |
+
nltk.download('averaged_perceptron_tagger')
|
23 |
+
|
24 |
+
class QuizGenerator:
|
25 |
+
def __init__(self):
|
26 |
+
# Initialize the summarizer and question generator models
|
27 |
+
self.summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
28 |
+
|
29 |
+
# Load question generation model
|
30 |
+
self.qg_model = AutoModelForSeq2SeqGeneration.from_pretrained("valhalla/t5-base-qg-hl")
|
31 |
+
self.qg_tokenizer = AutoTokenizer.from_pretrained("valhalla/t5-base-qg-hl")
|
32 |
+
|
33 |
+
# Initialize MCQ generation components
|
34 |
+
self.qa_model = pipeline('question-answering', model='distilbert-base-cased-distilled-squad')
|
35 |
+
|
36 |
+
def extract_text_from_pdf(self, pdf_file):
|
37 |
+
"""Extract text from a PDF file."""
|
38 |
+
try:
|
39 |
+
text = ""
|
40 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
41 |
+
for page in pdf_reader.pages:
|
42 |
+
text += page.extract_text() + "\n"
|
43 |
+
return text
|
44 |
+
except Exception as e:
|
45 |
+
logger.error(f"Error extracting text from PDF: {e}")
|
46 |
+
return ""
|
47 |
+
|
48 |
+
def extract_text_from_docx(self, docx_file):
|
49 |
+
"""Extract text from a DOCX file."""
|
50 |
+
try:
|
51 |
+
doc = docx.Document(docx_file)
|
52 |
+
text = ""
|
53 |
+
for para in doc.paragraphs:
|
54 |
+
text += para.text + "\n"
|
55 |
+
return text
|
56 |
+
except Exception as e:
|
57 |
+
logger.error(f"Error extracting text from DOCX: {e}")
|
58 |
+
return ""
|
59 |
+
|
60 |
+
def extract_text_from_txt(self, txt_file):
|
61 |
+
"""Extract text from a TXT file."""
|
62 |
+
try:
|
63 |
+
return txt_file.read().decode('utf-8')
|
64 |
+
except Exception as e:
|
65 |
+
logger.error(f"Error extracting text from TXT: {e}")
|
66 |
+
return ""
|
67 |
+
|
68 |
+
def get_youtube_transcript(self, video_id):
|
69 |
+
"""Extract transcript from a YouTube video."""
|
70 |
+
try:
|
71 |
+
transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
|
72 |
+
transcript = ' '.join([item['text'] for item in transcript_list])
|
73 |
+
return transcript
|
74 |
+
except Exception as e:
|
75 |
+
logger.error(f"Error getting YouTube transcript: {e}")
|
76 |
+
return ""
|
77 |
+
|
78 |
+
def summarize_text(self, text, max_length=1000):
|
79 |
+
"""Summarize long text to make processing more efficient."""
|
80 |
+
if len(text) <= max_length:
|
81 |
+
return text
|
82 |
+
|
83 |
+
chunks = self._split_text_into_chunks(text, max_length=3000)
|
84 |
+
summaries = []
|
85 |
+
|
86 |
+
for chunk in chunks:
|
87 |
+
if len(chunk) < 100: # Skip chunks that are too small
|
88 |
+
continue
|
89 |
+
|
90 |
+
summary = self.summarizer(chunk, max_length=300, min_length=100, do_sample=False)
|
91 |
+
summaries.append(summary[0]['summary_text'])
|
92 |
+
|
93 |
+
return " ".join(summaries)
|
94 |
+
|
95 |
+
def _split_text_into_chunks(self, text, max_length=3000):
|
96 |
+
"""Split text into chunks of max_length characters."""
|
97 |
+
sentences = sent_tokenize(text)
|
98 |
+
chunks = []
|
99 |
+
current_chunk = ""
|
100 |
+
|
101 |
+
for sentence in sentences:
|
102 |
+
if len(current_chunk) + len(sentence) <= max_length:
|
103 |
+
current_chunk += " " + sentence
|
104 |
+
else:
|
105 |
+
chunks.append(current_chunk.strip())
|
106 |
+
current_chunk = sentence
|
107 |
+
|
108 |
+
if current_chunk:
|
109 |
+
chunks.append(current_chunk.strip())
|
110 |
+
|
111 |
+
return chunks
|
112 |
+
|
113 |
+
def generate_questions(self, text, num_questions=5):
|
114 |
+
"""Generate questions based on the input text."""
|
115 |
+
try:
|
116 |
+
# Summarize text if it's too long
|
117 |
+
processed_text = self.summarize_text(text)
|
118 |
+
|
119 |
+
# Split into sentences
|
120 |
+
sentences = sent_tokenize(processed_text)
|
121 |
+
|
122 |
+
questions = []
|
123 |
+
random.shuffle(sentences) # Randomize to get different questions each time
|
124 |
+
|
125 |
+
for sentence in sentences[:min(num_questions * 3, len(sentences))]: # Process more sentences than needed
|
126 |
+
if len(sentence.split()) < 5: # Skip short sentences
|
127 |
+
continue
|
128 |
+
|
129 |
+
# Format for the question generation model
|
130 |
+
input_text = f"generate question: {sentence}"
|
131 |
+
|
132 |
+
# Generate question
|
133 |
+
inputs = self.qg_tokenizer.encode(input_text, return_tensors="pt", max_length=512, truncation=True)
|
134 |
+
outputs = self.qg_model.generate(inputs, max_length=64, num_beams=4, early_stopping=True)
|
135 |
+
question = self.qg_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
136 |
+
|
137 |
+
# Use QA model to get answer
|
138 |
+
qa_input = {
|
139 |
+
'question': question,
|
140 |
+
'context': processed_text
|
141 |
+
}
|
142 |
+
answer = self.qa_model(qa_input)
|
143 |
+
|
144 |
+
if answer['score'] > 0.1: # Only keep questions with reasonable confidence
|
145 |
+
questions.append({
|
146 |
+
'question': question,
|
147 |
+
'answer': answer['answer'],
|
148 |
+
'context': sentence
|
149 |
+
})
|
150 |
+
|
151 |
+
if len(questions) >= num_questions:
|
152 |
+
break
|
153 |
+
|
154 |
+
return questions
|
155 |
+
|
156 |
+
except Exception as e:
|
157 |
+
logger.error(f"Error generating questions: {e}")
|
158 |
+
return []
|
159 |
+
|
160 |
+
def generate_mcq(self, questions, num_options=4):
|
161 |
+
"""Convert open-ended questions to multiple-choice questions."""
|
162 |
+
mcqs = []
|
163 |
+
|
164 |
+
for q in questions:
|
165 |
+
correct_answer = q['answer']
|
166 |
+
|
167 |
+
# Generate distractors (incorrect options)
|
168 |
+
distractors = self._generate_distractors(q['context'], correct_answer, num_options-1)
|
169 |
+
|
170 |
+
# Create options list with correct answer
|
171 |
+
options = distractors + [correct_answer]
|
172 |
+
random.shuffle(options)
|
173 |
+
|
174 |
+
# Find position of correct answer
|
175 |
+
correct_index = options.index(correct_answer)
|
176 |
+
|
177 |
+
mcqs.append({
|
178 |
+
'question': q['question'],
|
179 |
+
'options': options,
|
180 |
+
'correct_answer': correct_answer,
|
181 |
+
'correct_index': correct_index
|
182 |
+
})
|
183 |
+
|
184 |
+
return mcqs
|
185 |
+
|
186 |
+
def _generate_distractors(self, context, correct_answer, num_distractors=3):
|
187 |
+
"""Generate plausible but incorrect answers."""
|
188 |
+
# Simple approach - extract other nouns from the text
|
189 |
+
words = nltk.word_tokenize(context)
|
190 |
+
pos_tags = nltk.pos_tag(words)
|
191 |
+
|
192 |
+
# Extract nouns and named entities
|
193 |
+
nouns = [word for word, pos in pos_tags if pos in ('NN', 'NNS', 'NNP', 'NNPS') and word.lower() != correct_answer.lower()]
|
194 |
+
|
195 |
+
# Deduplicate and filter
|
196 |
+
unique_nouns = list(set(nouns))
|
197 |
+
distractors = [noun for noun in unique_nouns if len(noun) > 2]
|
198 |
+
|
199 |
+
# If we don't have enough distractors, add some generic ones
|
200 |
+
generic_distractors = ["None of the above", "Cannot be determined", "All of the above"]
|
201 |
+
|
202 |
+
# Combine and return required number
|
203 |
+
combined = list(distractors) + generic_distractors
|
204 |
+
random.shuffle(combined)
|
205 |
+
|
206 |
+
return combined[:num_distractors]
|
207 |
+
|
208 |
+
def generate_true_false(self, text, num_questions=5):
|
209 |
+
"""Generate true/false questions from text."""
|
210 |
+
try:
|
211 |
+
# Generate factual statements first
|
212 |
+
questions = self.generate_questions(text, num_questions)
|
213 |
+
true_false = []
|
214 |
+
|
215 |
+
for q in questions:
|
216 |
+
# Original statement is true
|
217 |
+
true_statement = {
|
218 |
+
'statement': q['context'],
|
219 |
+
'is_true': True
|
220 |
+
}
|
221 |
+
|
222 |
+
# Create a false version by negating or changing key parts
|
223 |
+
words = q['context'].split()
|
224 |
+
if len(words) > 4:
|
225 |
+
# Simple modification: replace a word or add a negation
|
226 |
+
change_idx = random.randint(0, len(words)-1)
|
227 |
+
words[change_idx] = random.choice(["not", "never", "rarely", "incorrectly"]) + " " + words[change_idx]
|
228 |
+
false_statement = {
|
229 |
+
'statement': " ".join(words),
|
230 |
+
'is_true': False
|
231 |
+
}
|
232 |
+
|
233 |
+
true_false.extend([true_statement, false_statement])
|
234 |
+
|
235 |
+
# Shuffle and return required number
|
236 |
+
random.shuffle(true_false)
|
237 |
+
return true_false[:num_questions]
|
238 |
+
|
239 |
+
except Exception as e:
|
240 |
+
logger.error(f"Error generating true/false questions: {e}")
|
241 |
+
return []
|
242 |
+
|
243 |
+
def create_streamlit_app():
|
244 |
+
st.set_page_config(page_title="QuizWhiz", page_icon="📚", layout="wide")
|
245 |
+
|
246 |
+
st.title("QuizWhiz - Comprehensive Quiz Generator")
|
247 |
+
st.subheader("Generate quizzes from various sources: text, documents, and YouTube videos")
|
248 |
+
|
249 |
+
quiz_gen = QuizGenerator()
|
250 |
+
|
251 |
+
# Sidebar for options
|
252 |
+
st.sidebar.header("Quiz Options")
|
253 |
+
quiz_type = st.sidebar.selectbox(
|
254 |
+
"Question Type",
|
255 |
+
["Multiple Choice", "True/False", "Open-Ended"]
|
256 |
+
)
|
257 |
+
|
258 |
+
num_questions = st.sidebar.slider("Number of Questions", 3, 20, 5)
|
259 |
+
|
260 |
+
# Source selection
|
261 |
+
st.header("Select Your Content Source")
|
262 |
+
source_type = st.radio(
|
263 |
+
"Content Source",
|
264 |
+
["Text Input", "Document Upload", "YouTube Video", "Topic/Subject"]
|
265 |
+
)
|
266 |
+
|
267 |
+
text_content = ""
|
268 |
+
|
269 |
+
# Handle different source types
|
270 |
+
if source_type == "Text Input":
|
271 |
+
text_content = st.text_area("Enter your text content here:", height=250)
|
272 |
+
|
273 |
+
elif source_type == "Document Upload":
|
274 |
+
uploaded_file = st.file_uploader("Upload your document", type=['pdf', 'docx', 'txt'])
|
275 |
+
|
276 |
+
if uploaded_file is not None:
|
277 |
+
st.success(f"File '{uploaded_file.name}' uploaded successfully!")
|
278 |
+
|
279 |
+
# Extract text based on file type
|
280 |
+
if uploaded_file.name.endswith('.pdf'):
|
281 |
+
text_content = quiz_gen.extract_text_from_pdf(uploaded_file)
|
282 |
+
elif uploaded_file.name.endswith('.docx'):
|
283 |
+
text_content = quiz_gen.extract_text_from_docx(uploaded_file)
|
284 |
+
elif uploaded_file.name.endswith('.txt'):
|
285 |
+
text_content = quiz_gen.extract_text_from_txt(uploaded_file)
|
286 |
+
|
287 |
+
# Show text preview
|
288 |
+
if text_content:
|
289 |
+
with st.expander("Preview Extracted Text"):
|
290 |
+
st.text(text_content[:500] + "..." if len(text_content) > 500 else text_content)
|
291 |
+
else:
|
292 |
+
st.error("Failed to extract text from the document.")
|
293 |
+
|
294 |
+
elif source_type == "YouTube Video":
|
295 |
+
youtube_url = st.text_input("Enter YouTube Video URL:")
|
296 |
+
|
297 |
+
if youtube_url:
|
298 |
+
# Extract video ID from URL
|
299 |
+
video_id_match = re.search(r'(?:v=|\/)([0-9A-Za-z_-]{11}).*', youtube_url)
|
300 |
+
|
301 |
+
if video_id_match:
|
302 |
+
video_id = video_id_match.group(1)
|
303 |
+
|
304 |
+
# Show video embed
|
305 |
+
st.video(youtube_url)
|
306 |
+
|
307 |
+
# Extract transcript
|
308 |
+
with st.spinner("Extracting video transcript..."):
|
309 |
+
text_content = quiz_gen.get_youtube_transcript(video_id)
|
310 |
+
|
311 |
+
if text_content:
|
312 |
+
with st.expander("Preview Transcript"):
|
313 |
+
st.text(text_content[:500] + "..." if len(text_content) > 500 else text_content)
|
314 |
+
else:
|
315 |
+
st.error("Failed to extract transcript. This video might not have captions.")
|
316 |
+
else:
|
317 |
+
st.error("Invalid YouTube URL. Please enter a valid URL.")
|
318 |
+
|
319 |
+
elif source_type == "Topic/Subject":
|
320 |
+
topic = st.text_input("Enter a topic or subject:")
|
321 |
+
|
322 |
+
if topic:
|
323 |
+
# For this demo, we'll use a predefined text about the topic
|
324 |
+
# In a real app, you might use an API to fetch content about the topic
|
325 |
+
st.info(f"Generating quiz about: {topic}")
|
326 |
+
text_content = f"The topic of {topic} is a fascinating subject to explore. " \
|
327 |
+
f"There are many important concepts and facts related to {topic} " \
|
328 |
+
f"that make it an essential area of study. Understanding {topic} " \
|
329 |
+
f"requires careful consideration of its key principles."
|
330 |
+
|
331 |
+
# Placeholder for a real implementation that would gather information about the topic
|
332 |
+
st.warning("In a complete implementation, this would gather information about the topic from reliable sources.")
|
333 |
+
|
334 |
+
# Generate Quiz Button
|
335 |
+
if text_content:
|
336 |
+
if st.button("Generate Quiz"):
|
337 |
+
with st.spinner("Generating quiz questions..."):
|
338 |
+
if quiz_type == "Multiple Choice":
|
339 |
+
# Generate questions first
|
340 |
+
questions = quiz_gen.generate_questions(text_content, num_questions)
|
341 |
+
# Convert to MCQs
|
342 |
+
mcqs = quiz_gen.generate_mcq(questions)
|
343 |
+
|
344 |
+
if mcqs:
|
345 |
+
st.success(f"Generated {len(mcqs)} multiple choice questions!")
|
346 |
+
|
347 |
+
# Display questions
|
348 |
+
for i, q in enumerate(mcqs, 1):
|
349 |
+
st.subheader(f"Question {i}: {q['question']}")
|
350 |
+
|
351 |
+
# Display options
|
352 |
+
option_letters = ['A', 'B', 'C', 'D']
|
353 |
+
for j, option in enumerate(q['options']):
|
354 |
+
st.write(f"{option_letters[j]}. {option}")
|
355 |
+
|
356 |
+
# Reveal answer in expander
|
357 |
+
with st.expander("Reveal Answer"):
|
358 |
+
st.write(f"Correct Answer: {option_letters[q['correct_index']]}. {q['correct_answer']}")
|
359 |
+
|
360 |
+
st.divider()
|
361 |
+
else:
|
362 |
+
st.error("Failed to generate questions. Try with different content.")
|
363 |
+
|
364 |
+
elif quiz_type == "True/False":
|
365 |
+
tf_questions = quiz_gen.generate_true_false(text_content, num_questions)
|
366 |
+
|
367 |
+
if tf_questions:
|
368 |
+
st.success(f"Generated {len(tf_questions)} true/false questions!")
|
369 |
+
|
370 |
+
# Display questions
|
371 |
+
for i, q in enumerate(tf_questions, 1):
|
372 |
+
st.subheader(f"Question {i}: True or False?")
|
373 |
+
st.write(q['statement'])
|
374 |
+
|
375 |
+
# Reveal answer
|
376 |
+
with st.expander("Reveal Answer"):
|
377 |
+
st.write(f"Answer: {'True' if q['is_true'] else 'False'}")
|
378 |
+
|
379 |
+
st.divider()
|
380 |
+
else:
|
381 |
+
st.error("Failed to generate true/false questions. Try with different content.")
|
382 |
+
|
383 |
+
elif quiz_type == "Open-Ended":
|
384 |
+
questions = quiz_gen.generate_questions(text_content, num_questions)
|
385 |
+
|
386 |
+
if questions:
|
387 |
+
st.success(f"Generated {len(questions)} open-ended questions!")
|
388 |
+
|
389 |
+
# Display questions
|
390 |
+
for i, q in enumerate(questions, 1):
|
391 |
+
st.subheader(f"Question {i}: {q['question']}")
|
392 |
+
|
393 |
+
# Reveal answer
|
394 |
+
with st.expander("Reveal Answer"):
|
395 |
+
st.write(f"Suggested Answer: {q['answer']}")
|
396 |
+
st.write(f"Context: {q['context']}")
|
397 |
+
|
398 |
+
st.divider()
|
399 |
+
else:
|
400 |
+
st.error("Failed to generate questions. Try with different content.")
|
401 |
+
else:
|
402 |
+
st.info("Please provide content or select a source to generate a quiz.")
|
403 |
+
|
404 |
+
# Footer
|
405 |
+
st.sidebar.divider()
|
406 |
+
st.sidebar.caption("QuizWhiz - Powered by AI")
|
407 |
+
st.sidebar.caption("© 2025 QuizWhiz Technologies")
|
408 |
+
|
409 |
+
if __name__ == "__main__":
|
410 |
+
create_streamlit_app()
|