Add utils.filter_objects(...) and Page.filter(...)

This commit is contained in:
Jeremy Singer-Vine
2016-03-08 09:47:23 -05:00
parent 50e89fd570
commit 381bc6ba02
3 changed files with 38 additions and 1 deletions
+17 -1
View File
@@ -180,10 +180,12 @@ class Page(Container):
x_tolerance=x_tolerance,
y_tolerance=y_tolerance)
def crop(self, bbox, strict=False):
return CroppedPage(self, bbox, strict=strict)
def filter(self, fn):
return FilteredPage(self, fn)
class CroppedPage(Page):
def __init__(self, parent_page, bbox, strict=False):
self.parent_page = parent_page
@@ -202,3 +204,17 @@ class CroppedPage(Page):
self.bbox,
**kwargs)
return self._objects
class FilteredPage(Page):
def __init__(self, parent_page, fn):
self.parent_page = parent_page
self.fn = fn
@property
def objects(self):
if hasattr(self, "_objects"): return self._objects
self._objects = utils.filter_objects(
self.parent_page.objects,
self.fn
)
return self._objects
+10
View File
@@ -195,6 +195,16 @@ def find_gutters(chars, orientation, min_size=5):
gutters = gutters + [ end_max + Decimal('0.001') ]
return gutters
def filter_objects(objs, fn):
if isinstance(objs, dict):
return dict((k, filter_objects(v, fn))
for k,v in objs.items())
initial_type = type(objs)
objs = to_list(objs)
filtered = filter(fn, objs)
return initial_type(filtered)
def point_inside_bbox(point, bbox):
px, py = point
@@ -101,3 +101,14 @@ class Test(unittest.TestCase):
month_chars = within_bbox(page.chars, (0, 35, self.PDF_WIDTH, 65))
month_text = collate_chars(month_chars, x_tolerance=2)
assert(month_text == "November - 2015")
def test_filter(self):
page = self.pdf.pages[0]
def test(obj):
if obj["object_type"] == "char":
if obj["size"] < 20:
return False
return True
filtered = page.filter(test)
text = filtered.extract_text(x_tolerance=2)
assert(text == "NICS Firearm Background Checks\nNovember - 2015")