File size: 4,905 Bytes
84ae4aa
 
 
 
 
0966694
 
 
84ae4aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76d79d9
9a7793f
84ae4aa
76d79d9
84ae4aa
 
 
 
35c8195
 
 
 
76d79d9
84ae4aa
 
9a7793f
84ae4aa
 
 
 
 
76d79d9
84ae4aa
 
 
 
 
 
 
 
 
37f919d
 
84ae4aa
37f919d
 
2f31a54
37f919d
 
84ae4aa
 
 
37f919d
84ae4aa
76d79d9
9a7793f
84ae4aa
 
 
 
 
76d79d9
84ae4aa
2f31a54
84ae4aa
37f919d
84ae4aa
 
35c8195
 
84ae4aa
2f31a54
 
 
84ae4aa
 
76d79d9
37f919d
84ae4aa
 
76d79d9
84ae4aa
 
9a7793f
84ae4aa
 
37f919d
2f31a54
37f919d
 
 
 
 
 
 
 
84ae4aa
35c8195
 
 
 
 
84ae4aa
 
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
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()