ExtraQ-GEM / app.py
MojoHz's picture
Update app.py
35c8195 verified
import streamlit as st
import google.generativeai as genai
import PyPDF2
import io
# Manually set your API key here
API_KEY = "AIzaSyBU_CBGCFbqdhOy5-xjPOQT-CUsLrclrtE" # Replace this with your actual API key
genai.configure(api_key=API_KEY)
# Initialize the Generative Model
model = genai.GenerativeModel('gemini-pro')
def extract_text_from_pdf(pdf_file):
"""Extract text from the given PDF file."""
try:
text = ""
pdf_file.seek(0)
reader = PyPDF2.PdfReader(io.BytesIO(pdf_file.read()))
for page in reader.pages:
text += page.extract_text()
return text
except Exception as e:
return f"Error extracting text from PDF: {e}"
def generate_quiz(text, difficulty, num_questions):
"""Generate a quiz based on the provided text, difficulty, and number of questions."""
try:
prompt = (f"Based on the following text, generate a quiz with a maximum of {num_questions} questions. "
"Include both questions and answers in the format of question and answer pairs. "
"Adjust the difficulty to {difficulty} level:\n\n"
f"{text}\n\n"
"Please provide the quiz in the format of:\n"
"Question1: Question 1?\n"
"Answer1: Answer to Question 1\n"
"Question2: Question 2?\n"
"Answer2: Answer to Question 2\n"
"... and so on. Limit the total number of questions to {num_questions}.")
response = model.generate_content(prompt)
# Limit the response to the number of questions requested
lines = response.text.split('\n')
limited_quiz = []
question_count = 0
for line in lines:
if line.startswith('Q') and question_count >= num_questions:
break
if line.startswith('Q'):
question_count += 1
limited_quiz.append(line)
return '\n'.join(limited_quiz)
except Exception as e:
return f"Error generating quiz: {e}"
def answer_question_from_quiz(question):
"""Answer the user's question based on the generated quiz."""
try:
prompt = (f"Based on the following quiz, answer the user's question. The quiz is formatted with "
"questions followed by answers:\n\n"
f"{st.session_state.generated_quiz}\n\n"
f"User's question: {question}\n\n"
"Please provide a detailed answer based on the quiz content.")
response = model.generate_content(prompt)
return response.text
except Exception as e:
return f"Error answering question: {e}"
def process_pdf(pdf_file, difficulty, num_questions):
"""Process the uploaded PDF to generate and explain quiz questions."""
try:
# Extract text from the PDF
extracted_text = extract_text_from_pdf(pdf_file)
# Generate a new quiz based on the extracted text
st.session_state.generated_quiz = generate_quiz(extracted_text, difficulty, num_questions)
return st.session_state.generated_quiz
except Exception as e:
return f"Error processing PDF: {e}"
def main():
st.title("Welcome to ExtraQ!")
st.write("Please upload an exam or quiz PDF to generate a new quiz with the same style, while having the freedom to change complexity. You can also ask questions based on the generated quiz. This is a student project, with no funds and professional team to follow it regularly, so apologies if any inconvenience happens, I will try my best to improve this project as the time passes by!")
if 'generated_quiz' not in st.session_state:
st.session_state.generated_quiz = ""
uploaded_file = st.file_uploader("Upload PDF", type=["pdf"])
difficulty = st.selectbox("Difficulty Level", ['easy', 'medium', 'hard'])
num_questions = st.selectbox("Number of Questions", [2, 4, 6, 8, 10])
if st.button("Generate Quiz"):
if uploaded_file is not None:
st.session_state.generated_quiz = process_pdf(uploaded_file, difficulty, num_questions)
st.subheader("Generated Quiz")
st.text(st.session_state.generated_quiz)
else:
st.error("Please upload a PDF file.")
if st.session_state.generated_quiz:
question = st.text_input("Ask a question about the quiz", "")
if st.button("Ask"):
if question:
answer = answer_question_from_quiz(question)
st.subheader("Answer")
st.text(answer)
else:
st.error("Please type a question to get an answer.")
# Add credits section
st.markdown("---")
st.markdown("*Developed for NU Students by Mohamed Hafez*")
if __name__ == "__main__":
main()