NameError Traceback (most recent call last)
in <cell line: 59>()
57
58 # Usage
---> 59 pdf_text = read_pdf("chapter-2.pdf")
60 questions = get_mca_questions(pdf_text)
61 for question in questions:
in read_pdf(file)
49 # Read PDF file
50 def read_pdf(file):
---> 51 pdf = PdfReader(file)
52 text = ''
53 num_pages = len(pdf.pages)
To supress warnings
import warnings
warnings.filterwarnings("ignore")
!pip install transformers
!pip install PyPDF4
from PyPDF4 import PdfFileReader
import io
def read_pdf(file):
pdf = PdfFileReader(file)
text = ''
for page in range(pdf.getNumPages()):
text += pdf.getPage(page).extractText()
return text
from transformers import pipeline, set_seed
import re
def get_mca_questions(context: str):
# Check if the input is a string
if not isinstance(context, str):
raise ValueError("Input should be a string")
# Initialize the GPT-2 model
generator = pipeline('text-generation', model='gpt2')
set_seed(42)
# Generate questions
mca_questions = []
prompts = ["Create a multiple choice question based on the following context:",
"Formulate an objective question with multiple correct answers from the following text:"]
for prompt in prompts:
# Generate text
text = generator(f"{prompt} {context}", max_length=200, num_return_sequences=5)
# Extract the question and options from the generated text
for t in text:
question = re.findall(r'Q1:(.*?)(a.|A.)', t['generated_text'])
options = re.findall(r'(a.|b.|c.|d.)(.*?)(a.|b.|c.|d.|Correct)', t['generated_text'])
correct = re.findall(r'Correct Options:(.*?)(Q1|$)', t['generated_text'])
if question and options and correct:
mca_questions.append({"question": question[0][0].strip(),
"options": [option[1].strip() for option in options],
"correct": correct[0][0].strip()})
return mca_questions
Read PDF file
def read_pdf(file):
pdf = PdfReader(file)
text = ''
num_pages = len(pdf.pages)
for page in range(num_pages):
text += pdf.pages[page].extract_text()
return text
Usage
pdf_text = read_pdf("chapter-2.pdf")
questions = get_mca_questions(pdf_text)
for question in questions:
print(f"Question: {question['question']}")
print(f"Options")
Receiving the below error for the above code. modify and give me a perfect final code:
NameError: name 'PdfReader' is not defined