def log(self, message, color):
"""Log messages with color."""
print(termcolor.colored(message, color))
def extract_text_from_pdf(self):
"""Extract text from each page of the PDF."""
self.log(f"Starting text extraction from {self.pdf_path}...", "cyan")
try:
with open(self.pdf_path, 'rb') as file:
reader = PdfReader(file)
self.pages_text = [page.extract_text() for page in reader.pages]
self.log(f"Extracted text from {len(self.pages_text)} pages.", "green")
except Exception as e:
self.log(f"Error extracting text from PDF: {str(e)}", "red")
# ABSTRACT EXTRACTION
def find_abstract_page(self):
"""Find the page containing the abstract."""
self.log("Searching for abstract page...", "cyan")
for i, page in enumerate(self.pages_text):
if re.search(r"\b(?:Abstract|Abstrak)\b", page, re.IGNORECASE):
self.abstract_page_index = i
self.abstract_page_content = page
self.log(f"Abstract found on page {self.abstract_page_index + 1}.", "green")
return
self.log("No abstract found in the document.", "yellow")
self.abstract_page_index = None
self.abstract_page_content = None
def extract_abstract(self, gpt_instance):
"""Extract the abstract using GPT instance."""
if self.abstract_page_content:
start_point = "You are a paper abstract extractor. You will meet papers from different languages, prioritize Indonesian output. Your job is to analyze the text snippet you receive and extract the abstract out of it."
self.log("Passing the abstract content to GPT for extraction...", "cyan")
try:
gpt_response = gpt_instance(start_point, self.abstract_page_content)
print(termcolor.colored(f"PAGE:\n\n{self.abstract_page_content}", "yellow"))
self.log(f"Found Abstract on Page {self.abstract_page_index + 1}", "green")
print(termcolor.colored(f"ABSTRACT:\n\n{gpt_response}", "light_magenta"))
return gpt_response
except Exception as e:
self.log(f"Error during GPT extraction: {str(e)}", "red")
else:
self.log("[Paper contains no abstract]", "yellow")
return None
# REFERENCES EXTRACTION
def find_references_section(self):
"""Find the start of the References section."""
self.log("Searching for References section...", "cyan")
references_pattern = r"\b(?:References|Referensi|Daftar Pustaka)\b"
appendix_pattern = r"\b(?:Appendix|Lampiran)\b"
for i, page in enumerate(self.pages_text):
if re.search(references_pattern, page, re.IGNORECASE):
if self.references_start_index is None:
self.references_start_index = i
self.references_content = page
else:
self.references_content += page # Append content if References span multiple pages
# Stop capturing if Appendix appears
if re.search(appendix_pattern, page, re.IGNORECASE):
self.log("Reached Appendix section. Stopping References extraction.", "yellow")
break
if self.references_start_index is not None:
self.log(f"References section starts on page {self.references_start_index + 1}.", "green")
else:
self.log("No References section found in the document.", "yellow")
def extract_individual_references(self, gpt_instance):
"""Extract individual references using GPT instance."""
if not self.references_content:
self.log("No References content to extract.", "yellow")
return []
self.log("Passing References content to GPT for individual references extraction...", "cyan")
try:
prompt = (
"You are a paper references extractor. Your job is to analyze text snippet you receive "
"and extract individual references out of it. The output must be a list of references."
)
gpt_response = gpt_instance(prompt, self.references_content)
self.log("Successfully extracted individual references using GPT.", "green")
references = gpt_response.split("\n") # Split by newline in case GPT returns references in a list format
references = [ref.strip() for ref in references if ref.strip()] # Remove empty entries and strip whitespace
for i, ref in enumerate(references, 1):
self.log(f"Reference {i}: {ref[:100]}...", "light_magenta") # Print a snippet of each reference
return references
except Exception as e:
self.log(f"Error during GPT extraction: {str(e)}", "red")
return []
def process(self, gpt_instance):
"""Process the PDF to extract abstract and references."""
self.extract_text_from_pdf()
# Abstract extraction
self.find_abstract_page()
abstract = self.extract_abstract(gpt_instance)
# References extraction
self.find_references_section()
references = self.extract_individual_references(gpt_instance)
return {"abstract": abstract, "references": references}
Example usage
if name == "main":
pdf_path = 'C://Users//Name//Downloads//pdf_test//sample.pdf'
code
# Mock GPT instance for testing (replace with your actual gpt_instance)
def mock_gpt_instance(prompt, content):
# Simulated GPT output for testing purposes
if "abstract extractor" in prompt:
return "Extracted Abstract Text"
elif "references extractor" in prompt:
return (
"1. Author A, Title A, Journal A, 2020.\n"
"2. Author B, Title B, Journal B, 2021.\n"
"3. Author C, Title C, Journal C, 2022."
)
return ""
extractor = PDFContentExtractor(pdf_path)
result = extractor.process(mock_gpt_instance)
print(result)
To update the event handler for the new changes made in parser.py, you will likely want to ensure that it correctly handles the structures and outputs produced by the updated PDFContentExtractor class. Below is an event handler example that supports the methods and outputs from the modified parser.py class.
Make sure your event handler (possibly attached to a GUI or CLI interaction) follows the updated structure and methods of the PDFContentExtractor. Below is a sample implementation for an event handler that utilizes the updated functionality.
python
# eventhandler.py
class PDFEventHandler:
def __init__(self, gpt_instance):
self.gpt_instance = gpt_instance
def handle_pdf_upload(self, pdf_path):
"""Handle the upload and processing of a PDF file."""
extractor = PDFContentExtractor(pdf_path)
result = extractor.process(self.gpt_instance)
# Handle and display results
self.display_results(result)
def display_results(self, result):
"""Display the extracted abstract and references."""
abstract = result["abstract"]
references = result["references"]
if abstract:
print(termcolor.colored("Extracted Abstract:", "green"))
print(termcolor.colored(abstract, "light_magenta"))
else:
print(termcolor.colored("No abstract found.", "yellow"))
if references:
print(termcolor.colored("Extracted References:", "green"))
for i, ref in enumerate(references, 1):
print(termcolor.colored(f"{i}. {ref}", "light_magenta"))
else:
print(termcolor.colored("No references found.", "yellow"))
# Example usage of the event handler
if __name__ == "__main__":
pdf_path = "C://Users//Name//Downloads//pdf_test//sample.pdf"
# Mock GPT instance for testing (replace with your actual gpt_instance)
def mock_gpt_instance(prompt, content):
# Simulated GPT output for testing purposes
if "abstract extractor" in prompt:
return "Extracted Abstract Text"
elif "references extractor" in prompt:
return (
"1. Author A, Title A, Journal A, 2020.\n"
"2. Author B, Title B, Journal B, 2021.\n"
"3. Author C, Title C, Journal C, 2022."
)
return ""
# Creating an event handler instance
event_handler = PDFEventHandler(mock_gpt_instance)
event_handler.handle_pdf_upload(pdf_path)
Explanation of Changes:
Integration with the Extractor: The PDFEventHandler class has been created to encapsulate the event handling operations associated with PDF file processing.
PDF Processing: The handle_pdf_upload method takes care of initializing the PDFContentExtractor and invoking its process method with the mock GPT instance.
Result Handling: The display_results method neatly presents the extracted abstract and references. It formats the output using termcolor for better visibility in the terminal.
Mock GPT Instance: Similar to your example, a mock implementation of the GPT instance is provided to simulate responses during testing.
This handler can be extended or modified based on the specific requirements or user interface (CLI/GUI) where it's being plugged in. Make sure to replace the mock GPT instance with the actual implementation in your production environment.