import PyPDF2 import nltk import random import streamlit as st from openai import OpenAI from dotenv import load_dotenv import os from openai import ChatCompletion # Download NLTK data (if not already downloaded) nltk.download('punkt') # load the environment variables into the python script load_dotenv() # fetching the openai_api_key environment variable openai_api_key = os.getenv('OPENAI_API_KEY') def extract_text_from_pdf(pdf_file): pdf_reader = PyPDF2.PdfReader(pdf_file) text = "" for page_num in range(len(pdf_reader.pages)): text += pdf_reader.pages[page_num].extract_text() return text def generate_mcqs_on_topic(text, topic, num_mcqs=5): # Tokenize the text into sentences sentences = nltk.sent_tokenize(text) # Randomly select sentences to create Questions selected_sentences = random.sample(sentences, min(num_mcqs, len(sentences))) mcqs = [] for sentence in selected_sentences: # Use ChatGPT for interactive question generation chatgpt_question = generate_question_with_chatgpt(sentence, topic) mcqs.append(chatgpt_question) return mcqs def generate_question_with_chatgpt(context, topic): # Initializing the default value generated_question = { 'content': "Unable to generate a question..", 'options': [], # assuming options is a list 'correct_answer': "Unknown" } data = { "model": "gpt-3.5-turbo", "temperature": 0.7, "max_tokens": 1024, "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": f"What is the question on {topic} for the following? {context}"}, ], } response = ChatCompletion.create(data) result = response.json() print("API Response:", result) # Add this line for debugging if 'choices' in result: # Extract the generated question, options, and correct answer from the response generated_question = { 'content': result["choices"][0]["message"]["content"], 'options': result["choices"][0]["message"].get("options", []), 'correct_answer': result["choices"][0]["message"].get("correct_answer", "Unknown") } else: print("Unexpected API response format.") return generated_question def main(): # Title of the Application st.header("🤖CB Quiz Generator🧠", divider='rainbow') st.subheader("☕CoffeeBeans☕") # User input pdf_file = st.file_uploader("Upload PDF Document:", type=["pdf"]) num_mcqs = st.number_input("Enter Number of MCQs to Generate:", min_value=1, step=1, value=5) topic = st.text_input("Enter the Topic in which the quiz has to be generated") # Button to trigger QUIZ generation if st.button("Generate Quiz"): if pdf_file: text = extract_text_from_pdf(pdf_file) mcqs = generate_mcqs_on_topic(text, topic, num_mcqs) # Display the generated Questions st.success(f"Generated {num_mcqs} Questions:") for i, generated_question in enumerate(mcqs, start=1): st.write(f"\nQuestion {i}: {generated_question['content']}") st.write(f"Options: {', '.join(generated_question['options'])}") st.write(f"Correct Answer: {generated_question['correct_answer']}") else: st.error("Please upload a PDF document.") if __name__ == "__main__": main()