arsalan16 commited on
Commit
28d0527
·
verified ·
1 Parent(s): 87ee274

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -53
app.py CHANGED
@@ -1,57 +1,101 @@
1
  import streamlit as st
2
  from transformers import pipeline
3
- import PyPDF2
4
-
5
- # Load the Hugging Face model
6
- @st.cache_resource # Caches the model to improve loading time
7
- def load_model():
8
- return pipeline("text2text-generation", model="t5-base")
9
-
10
- # Initialize the model
11
- question_generator = load_model()
12
-
13
- # Function to extract text from uploaded PDF
14
- def extract_text_from_pdf(pdf_file):
15
- pdf_reader = PyPDF2.PdfReader(pdf_file)
16
- extracted_text = ""
17
- for page in pdf_reader.pages:
18
- extracted_text += page.extract_text()
19
- return extracted_text
20
-
21
- # Streamlit App Layout
22
- st.title("AI-Powered Quiz Generator")
23
- st.write("Create quizzes from any topic, text input, or uploaded PDF files using AI.")
24
-
25
- # Input Section
26
- st.subheader("Input Options")
27
- input_text = st.text_area("Enter your text or topic here:", height=200)
28
-
29
- # PDF Upload Section
30
- uploaded_file = st.file_uploader("Or upload a PDF file to extract text:", type=["pdf"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  if uploaded_file:
32
- with st.spinner("Extracting text from the PDF..."):
33
- input_text = extract_text_from_pdf(uploaded_file)
34
- st.success("Text extracted from the uploaded PDF!")
35
- st.write("Extracted Text Preview:")
36
- st.write(input_text[:1000]) # Display a preview of the extracted text (first 1000 characters)
37
-
38
- # Button to generate questions
39
- if st.button("Generate Quiz"):
40
- if input_text.strip():
 
 
 
 
 
 
 
 
 
 
 
 
41
  st.subheader("Generated Questions")
42
- with st.spinner("Generating questions..."):
43
- # Generate questions with beam search
44
- questions = question_generator(
45
- input_text,
46
- max_length=50,
47
- num_beams=5, # Enable beam search
48
- num_return_sequences=5 # Return multiple outputs
49
- )
50
- for i, question in enumerate(questions):
51
- st.write(f"{i+1}. {question['generated_text']}")
52
- else:
53
- st.error("Please enter some text or upload a PDF file to generate the quiz!")
54
-
55
- # Footer
56
- st.markdown("---")
57
- st.markdown("**Created by [Engr Muhammad Arsalan]** | Powered by Hugging Face & Streamlit")
 
1
  import streamlit as st
2
  from transformers import pipeline
3
+ import pandas as pd
4
+ import nltk
5
+ import spacy
6
+ import random
7
+ from io import BytesIO
8
+
9
+ # Load the necessary Hugging Face models
10
+ question_generator = pipeline('text-generation', model='gpt2')
11
+ summarizer = pipeline('summarization', model='facebook/bart-large-cnn')
12
+ classifier = pipeline('zero-shot-classification', model='facebook/bart-large-mnli')
13
+
14
+ # Function to generate questions based on input
15
+ def generate_questions(text, num_questions=5, difficulty="Medium"):
16
+ questions = []
17
+
18
+ # Summarize the input text
19
+ summarized_text = summarizer(text, max_length=150, min_length=50, do_sample=False)[0]['summary_text']
20
+
21
+ # Generate questions based on the summarized text
22
+ for _ in range(num_questions):
23
+ prompt = f"Create a multiple choice question based on the following text: {summarized_text}"
24
+ question = question_generator(prompt, max_length=50, num_return_sequences=1)[0]['generated_text']
25
+
26
+ # Tag the question with a difficulty level
27
+ difficulty_label = classifier(question, candidate_labels=["Easy", "Medium", "Hard"])['labels'][0]
28
+ if difficulty_label == difficulty:
29
+ questions.append(question)
30
+
31
+ return questions
32
+
33
+ # Function to generate an answer key
34
+ def generate_answer_key(questions):
35
+ answer_key = {}
36
+ for q in questions:
37
+ # Provide dummy answers for now (to be replaced with actual logic)
38
+ answer_key[q] = "Correct answer here"
39
+ return answer_key
40
+
41
+ # Function to save quizzes as PDF (this is a simplified version)
42
+ def save_as_pdf(quiz):
43
+ from fpdf import FPDF
44
+
45
+ pdf = FPDF()
46
+ pdf.add_page()
47
+ pdf.set_font("Arial", size=12)
48
+
49
+ for i, (question, answer) in enumerate(quiz.items()):
50
+ pdf.cell(200, 10, txt=f"{i+1}. {question} - Answer: {answer}", ln=True)
51
+
52
+ pdf_output = BytesIO()
53
+ pdf.output(pdf_output)
54
+ pdf_output.seek(0)
55
+ return pdf_output
56
+
57
+ # Streamlit Interface
58
+ st.title("Quiz Generator")
59
+ st.header("Create and Grade Quizzes")
60
+
61
+ # Step 1: Teacher input
62
+ topic = st.text_input("Enter topic or keywords for quiz generation:")
63
+ uploaded_file = st.file_uploader("Or upload text material (PDF, TXT):", type=["pdf", "txt"])
64
+
65
  if uploaded_file:
66
+ if uploaded_file.type == "text/plain":
67
+ input_text = uploaded_file.read().decode("utf-8")
68
+ elif uploaded_file.type == "application/pdf":
69
+ import PyPDF2
70
+ pdf_reader = PyPDF2.PdfReader(uploaded_file)
71
+ input_text = ""
72
+ for page in pdf_reader.pages:
73
+ input_text += page.extract_text()
74
+ else:
75
+ input_text = ""
76
+
77
+ # Generate quiz
78
+ if topic or input_text:
79
+ num_questions = st.slider("Number of questions:", 1, 10, 5)
80
+ difficulty = st.selectbox("Select difficulty:", ["Easy", "Medium", "Hard"])
81
+
82
+ if st.button("Generate Quiz"):
83
+ questions = generate_questions(input_text or topic, num_questions, difficulty)
84
+ answer_key = generate_answer_key(questions)
85
+
86
+ # Display the generated questions
87
  st.subheader("Generated Questions")
88
+ for i, question in enumerate(questions, 1):
89
+ st.write(f"{i}. {question}")
90
+
91
+ # Answer key
92
+ st.subheader("Answer Key")
93
+ for i, question in enumerate(questions, 1):
94
+ st.write(f"{i}. {answer_key[question]}")
95
+
96
+ # Save quiz as PDF
97
+ pdf_output = save_as_pdf(answer_key)
98
+ st.download_button("Download Quiz as PDF", data=pdf_output, file_name="quiz.pdf")
99
+ else:
100
+ st.warning("Please enter a topic or upload text material to generate a quiz.")
101
+