Skip to content

Commit

Permalink
linting
Browse files Browse the repository at this point in the history
  • Loading branch information
arinkulshi committed Apr 25, 2024
1 parent e59bbae commit 02518d2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 21 deletions.
2 changes: 1 addition & 1 deletion OCR/ocr/pdf_segmentor_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
extractor = PDFFieldExtractor(file_absolute_path)
extractor.initialize_reader()
extractor.segment_fields(["Region", "ParentGuardian"])
extractor.extract_images()
extractor.extract_images()
39 changes: 19 additions & 20 deletions OCR/ocr/services/pdf_field_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,41 @@
from PIL import Image
import os


class PDFFieldExtractor:
def __init__(self, file_path):
self.file_path = file_path
self.reader = None
self.reader = None
self.form_fields = []


def initialize_reader(self, base_path=None):
if base_path is None:
base_path = os.path.dirname(__file__)
full_path = os.path.join(base_path, self.file_path)
self.reader = PyPDF2.PdfReader(full_path)

def close_reader(self):
if self.reader is not None:
self.reader.stream.close() # Close the stream explicitly
self.reader = None

def segment_fields(self, field_names):
# Iterate through each page in the PDF
if self.reader is None:
raise ValueError("PDF reader is not initialized. Call initialize_reader() first.")
for page in self.reader.pages:
# Check if there are annotations (textboxes are considered annotations)
if '/Annots' in page:
annotations = page['/Annots']
for annot in annotations:
if isinstance(annot, PyPDF2.generic.IndirectObject):
annot = annot.get_object()
field = annot.get('/T')
rect = annot.get('/Rect')
if field and rect:
field_str = str(field)
if field_str in field_names:
self.form_fields.append((field_str, rect))
# Iterate through each page in the PDF
if self.reader is None:
raise ValueError("PDF reader is not initialized. Call initialize_reader() first.")
for page in self.reader.pages:
# Check if there are annotations (textboxes are considered annotations)
if "/Annots" in page:
annotations = page["/Annots"]
for annot in annotations:
if isinstance(annot, PyPDF2.generic.IndirectObject):
annot = annot.get_object()
field = annot.get("/T")
rect = annot.get("/Rect")
if field and rect:
field_str = str(field)
if field_str in field_names:
self.form_fields.append((field_str, rect))

def extract_images(self):
if self.reader is None:
Expand All @@ -55,4 +55,3 @@ def extract_images(self):
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
img.save(f'extracted_{field_name.replace("/", "_")}.png')
self.close_reader()

0 comments on commit 02518d2

Please sign in to comment.