natural-pdf 0.2.11__py3-none-any.whl → 0.2.13__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- natural_pdf/analyzers/guides.py +196 -43
- natural_pdf/core/highlighting_service.py +40 -10
- natural_pdf/core/page.py +56 -8
- natural_pdf/elements/base.py +15 -1
- natural_pdf/elements/region.py +37 -5
- natural_pdf/vision/__init__.py +1 -2
- natural_pdf/vision/mixin.py +67 -27
- natural_pdf/vision/results.py +49 -5
- natural_pdf/vision/similarity.py +195 -23
- natural_pdf/vision/template_matching.py +209 -0
- {natural_pdf-0.2.11.dist-info → natural_pdf-0.2.13.dist-info}/METADATA +1 -1
- {natural_pdf-0.2.11.dist-info → natural_pdf-0.2.13.dist-info}/RECORD +36 -15
- {natural_pdf-0.2.11.dist-info → natural_pdf-0.2.13.dist-info}/top_level.txt +1 -0
- temp/fix_page_exclusions.py +42 -0
- temp/test_draw_guides.py +25 -0
- temp/test_draw_guides_interactive.py +30 -0
- temp/test_exclusion_with_debug.py +30 -0
- temp/test_find_exclusions_fix.py +53 -0
- temp/test_find_exclusions_fix_no_recursion.py +97 -0
- temp/test_fix_real_pdf.py +48 -0
- temp/test_fix_working.py +55 -0
- temp/test_fixed_pdf_exclusions.py +67 -0
- temp/test_guide_draw_notebook.py +47 -0
- temp/test_horizontal_top_bottom.py +53 -0
- temp/test_inline_js.py +22 -0
- temp/test_marker_order.py +45 -0
- temp/test_original_exclusions_now_work.py +56 -0
- temp/test_pdf_exclusions_with_guides.py +84 -0
- temp/test_region_exclusions_detailed.py +25 -0
- temp/test_stripes_real_pdf.py +62 -0
- temp/test_vertical_stripes.py +55 -0
- temp/test_widget_functionality.py +68 -0
- temp/test_widget_simple.py +41 -0
- {natural_pdf-0.2.11.dist-info → natural_pdf-0.2.13.dist-info}/WHEEL +0 -0
- {natural_pdf-0.2.11.dist-info → natural_pdf-0.2.13.dist-info}/entry_points.txt +0 -0
- {natural_pdf-0.2.11.dist-info → natural_pdf-0.2.13.dist-info}/licenses/LICENSE +0 -0
natural_pdf/analyzers/guides.py
CHANGED
@@ -185,7 +185,9 @@ class GuidesList(UserList):
|
|
185
185
|
self,
|
186
186
|
markers: Union[str, List[str], "ElementCollection", Callable, None],
|
187
187
|
obj: Optional[Union["Page", "Region", "FlowRegion"]] = None,
|
188
|
-
align:
|
188
|
+
align: Union[
|
189
|
+
Literal["left", "right", "center", "between"], Literal["top", "bottom"]
|
190
|
+
] = "left",
|
189
191
|
outer: bool = True,
|
190
192
|
tolerance: float = 5,
|
191
193
|
*,
|
@@ -203,7 +205,10 @@ class GuidesList(UserList):
|
|
203
205
|
- Callable: function that takes a page and returns markers
|
204
206
|
- None: no markers
|
205
207
|
obj: Page/Region/FlowRegion to search (uses parent's context if None)
|
206
|
-
align: How to align guides relative to found elements
|
208
|
+
align: How to align guides relative to found elements:
|
209
|
+
- For vertical guides: 'left', 'right', 'center', 'between'
|
210
|
+
- For horizontal guides: 'top', 'bottom', 'center', 'between'
|
211
|
+
- Note: 'left'/'right' also work for horizontal (mapped to top/bottom)
|
207
212
|
outer: Whether to add outer boundary guides
|
208
213
|
tolerance: Tolerance for snapping to element edges
|
209
214
|
apply_exclusions: Whether to apply exclusion zones when searching for text
|
@@ -224,19 +229,25 @@ class GuidesList(UserList):
|
|
224
229
|
self._callable = None
|
225
230
|
actual_markers = markers
|
226
231
|
|
232
|
+
# Normalize alignment for horizontal guides
|
233
|
+
if self._axis == "horizontal":
|
234
|
+
if align == "top":
|
235
|
+
align = "left"
|
236
|
+
elif align == "bottom":
|
237
|
+
align = "right"
|
238
|
+
|
227
239
|
# Check if parent is in flow mode
|
228
240
|
if self._parent.is_flow_region:
|
229
241
|
# Create guides across all constituent regions
|
230
242
|
all_guides = []
|
231
243
|
for region in self._parent.context.constituent_regions:
|
232
|
-
#
|
233
|
-
marker_texts = _normalize_markers(actual_markers, region)
|
244
|
+
# Pass markers directly - from_content will handle them properly
|
234
245
|
|
235
246
|
# Create guides for this region
|
236
247
|
region_guides = Guides.from_content(
|
237
248
|
obj=region,
|
238
249
|
axis=self._axis,
|
239
|
-
markers=
|
250
|
+
markers=actual_markers, # Pass original markers, not normalized text
|
240
251
|
align=align,
|
241
252
|
outer=outer,
|
242
253
|
tolerance=tolerance,
|
@@ -312,14 +323,14 @@ class GuidesList(UserList):
|
|
312
323
|
return self._parent
|
313
324
|
|
314
325
|
# Original single-region logic
|
315
|
-
#
|
316
|
-
|
326
|
+
# Pass markers directly to from_content which will handle them properly
|
327
|
+
# (no need to normalize here since from_content now handles ElementCollection)
|
317
328
|
|
318
329
|
# Create guides for this axis
|
319
330
|
new_guides = Guides.from_content(
|
320
331
|
obj=target_obj,
|
321
332
|
axis=self._axis,
|
322
|
-
markers=
|
333
|
+
markers=actual_markers, # Pass original markers, not normalized text
|
323
334
|
align=align,
|
324
335
|
outer=outer,
|
325
336
|
tolerance=tolerance,
|
@@ -930,6 +941,82 @@ class GuidesList(UserList):
|
|
930
941
|
self.data.clear()
|
931
942
|
return self._parent
|
932
943
|
|
944
|
+
def from_stripes(
|
945
|
+
self,
|
946
|
+
stripes=None,
|
947
|
+
color=None, # Explicitly specify stripe color
|
948
|
+
) -> "Guides":
|
949
|
+
"""Create guides from striped table rows or columns.
|
950
|
+
|
951
|
+
Creates guides at both edges of stripe elements (e.g., colored table rows).
|
952
|
+
Perfect for zebra-striped tables where you need guides at every row boundary.
|
953
|
+
|
954
|
+
Args:
|
955
|
+
stripes: Elements representing stripes. If None, auto-detects.
|
956
|
+
color: Specific color to look for (e.g., '#00ffff'). If None, finds most common.
|
957
|
+
|
958
|
+
Examples:
|
959
|
+
# Auto-detect zebra stripes
|
960
|
+
guides.horizontal.from_stripes()
|
961
|
+
|
962
|
+
# Specific color
|
963
|
+
guides.horizontal.from_stripes(color='#00ffff')
|
964
|
+
|
965
|
+
# Manual selection
|
966
|
+
stripes = page.find_all('rect[fill=#00ffff]')
|
967
|
+
guides.horizontal.from_stripes(stripes)
|
968
|
+
|
969
|
+
# Vertical stripes
|
970
|
+
guides.vertical.from_stripes(color='#e0e0e0')
|
971
|
+
|
972
|
+
Returns:
|
973
|
+
Parent Guides object for chaining
|
974
|
+
"""
|
975
|
+
from collections import defaultdict
|
976
|
+
|
977
|
+
target_obj = self._parent.context
|
978
|
+
if target_obj is None:
|
979
|
+
raise ValueError("No context available for stripe detection")
|
980
|
+
|
981
|
+
if stripes is None:
|
982
|
+
if color:
|
983
|
+
# User specified color
|
984
|
+
stripes = target_obj.find_all(f"rect[fill={color}]")
|
985
|
+
else:
|
986
|
+
# Auto-detect most common non-white fill
|
987
|
+
all_rects = target_obj.find_all("rect[fill]")
|
988
|
+
|
989
|
+
# Group by fill color
|
990
|
+
fill_counts = defaultdict(list)
|
991
|
+
for rect in all_rects:
|
992
|
+
if rect.fill and rect.fill not in ["#ffffff", "white", "none", "transparent"]:
|
993
|
+
fill_counts[rect.fill].append(rect)
|
994
|
+
|
995
|
+
if not fill_counts:
|
996
|
+
return self._parent # No stripes found
|
997
|
+
|
998
|
+
# Find most common fill color
|
999
|
+
stripes = max(fill_counts.values(), key=len)
|
1000
|
+
|
1001
|
+
if not stripes:
|
1002
|
+
return self._parent
|
1003
|
+
|
1004
|
+
# Get both edges of each stripe
|
1005
|
+
edges = []
|
1006
|
+
if self._axis == "horizontal":
|
1007
|
+
for stripe in stripes:
|
1008
|
+
edges.extend([stripe.top, stripe.bottom])
|
1009
|
+
else:
|
1010
|
+
for stripe in stripes:
|
1011
|
+
edges.extend([stripe.x0, stripe.x1])
|
1012
|
+
|
1013
|
+
# Remove duplicates and sort
|
1014
|
+
edges = sorted(set(edges))
|
1015
|
+
|
1016
|
+
# Add guides
|
1017
|
+
self.extend(edges)
|
1018
|
+
return self._parent
|
1019
|
+
|
933
1020
|
def __add__(self, other):
|
934
1021
|
"""Handle addition of GuidesList objects by returning combined data."""
|
935
1022
|
if isinstance(other, GuidesList):
|
@@ -1459,7 +1546,9 @@ class Guides:
|
|
1459
1546
|
obj: Union["Page", "Region", "FlowRegion"],
|
1460
1547
|
axis: Literal["vertical", "horizontal"] = "vertical",
|
1461
1548
|
markers: Union[str, List[str], "ElementCollection", None] = None,
|
1462
|
-
align:
|
1549
|
+
align: Union[
|
1550
|
+
Literal["left", "right", "center", "between"], Literal["top", "bottom"]
|
1551
|
+
] = "left",
|
1463
1552
|
outer: bool = True,
|
1464
1553
|
tolerance: float = 5,
|
1465
1554
|
apply_exclusions: bool = True,
|
@@ -1475,7 +1564,9 @@ class Guides:
|
|
1475
1564
|
- List[str]: list of selectors or literal text strings
|
1476
1565
|
- ElementCollection: collection of elements to extract text from
|
1477
1566
|
- None: no markers
|
1478
|
-
align: Where to place guides relative to found text
|
1567
|
+
align: Where to place guides relative to found text:
|
1568
|
+
- For vertical guides: 'left', 'right', 'center', 'between'
|
1569
|
+
- For horizontal guides: 'top', 'bottom', 'center', 'between'
|
1479
1570
|
outer: Whether to add guides at the boundaries
|
1480
1571
|
tolerance: Maximum distance to search for text
|
1481
1572
|
apply_exclusions: Whether to apply exclusion zones when searching for text
|
@@ -1483,6 +1574,13 @@ class Guides:
|
|
1483
1574
|
Returns:
|
1484
1575
|
New Guides object aligned to text content
|
1485
1576
|
"""
|
1577
|
+
# Normalize alignment for horizontal guides
|
1578
|
+
if axis == "horizontal":
|
1579
|
+
if align == "top":
|
1580
|
+
align = "left"
|
1581
|
+
elif align == "bottom":
|
1582
|
+
align = "right"
|
1583
|
+
|
1486
1584
|
# Handle FlowRegion
|
1487
1585
|
if hasattr(obj, "constituent_regions"):
|
1488
1586
|
guides = cls(context=obj)
|
@@ -1530,39 +1628,51 @@ class Guides:
|
|
1530
1628
|
elif hasattr(obj, "width"):
|
1531
1629
|
bounds = (0, 0, obj.width, obj.height)
|
1532
1630
|
|
1533
|
-
#
|
1534
|
-
|
1631
|
+
# Handle different marker types
|
1632
|
+
elements_to_process = []
|
1535
1633
|
|
1536
|
-
#
|
1537
|
-
|
1538
|
-
|
1539
|
-
|
1540
|
-
|
1541
|
-
|
1542
|
-
|
1543
|
-
|
1544
|
-
|
1545
|
-
|
1546
|
-
|
1547
|
-
|
1548
|
-
|
1549
|
-
# For between, collect left edges for processing later
|
1550
|
-
guides_coords.append(element.x0)
|
1551
|
-
else: # horizontal
|
1552
|
-
if align == "left": # top for horizontal
|
1553
|
-
guides_coords.append(element.top)
|
1554
|
-
elif align == "right": # bottom for horizontal
|
1555
|
-
guides_coords.append(element.bottom)
|
1556
|
-
elif align == "center":
|
1557
|
-
guides_coords.append((element.top + element.bottom) / 2)
|
1558
|
-
elif align == "between":
|
1559
|
-
# For between, collect top edges for processing later
|
1560
|
-
guides_coords.append(element.top)
|
1634
|
+
# Check if markers is an ElementCollection or has elements attribute
|
1635
|
+
if hasattr(markers, "elements") or hasattr(markers, "_elements"):
|
1636
|
+
# It's an ElementCollection - use elements directly
|
1637
|
+
elements_to_process = getattr(markers, "elements", getattr(markers, "_elements", []))
|
1638
|
+
elif hasattr(markers, "__iter__") and not isinstance(markers, str):
|
1639
|
+
# Check if it's an iterable of elements (not strings)
|
1640
|
+
try:
|
1641
|
+
markers_list = list(markers)
|
1642
|
+
if markers_list and hasattr(markers_list[0], "x0"):
|
1643
|
+
# It's a list of elements
|
1644
|
+
elements_to_process = markers_list
|
1645
|
+
except:
|
1646
|
+
pass
|
1561
1647
|
|
1562
|
-
|
1563
|
-
|
1564
|
-
|
1565
|
-
|
1648
|
+
if elements_to_process:
|
1649
|
+
# Process elements directly without text search
|
1650
|
+
for element in elements_to_process:
|
1651
|
+
if axis == "vertical":
|
1652
|
+
if align == "left":
|
1653
|
+
guides_coords.append(element.x0)
|
1654
|
+
elif align == "right":
|
1655
|
+
guides_coords.append(element.x1)
|
1656
|
+
elif align == "center":
|
1657
|
+
guides_coords.append((element.x0 + element.x1) / 2)
|
1658
|
+
elif align == "between":
|
1659
|
+
# For between, collect left edges for processing later
|
1660
|
+
guides_coords.append(element.x0)
|
1661
|
+
else: # horizontal
|
1662
|
+
if align == "left": # top for horizontal
|
1663
|
+
guides_coords.append(element.top)
|
1664
|
+
elif align == "right": # bottom for horizontal
|
1665
|
+
guides_coords.append(element.bottom)
|
1666
|
+
elif align == "center":
|
1667
|
+
guides_coords.append((element.top + element.bottom) / 2)
|
1668
|
+
elif align == "between":
|
1669
|
+
# For between, collect top edges for processing later
|
1670
|
+
guides_coords.append(element.top)
|
1671
|
+
else:
|
1672
|
+
# Fall back to text-based search
|
1673
|
+
marker_texts = _normalize_markers(markers, obj)
|
1674
|
+
|
1675
|
+
# Find each marker and determine guide position
|
1566
1676
|
for marker in marker_texts:
|
1567
1677
|
if hasattr(obj, "find"):
|
1568
1678
|
element = obj.find(
|
@@ -1570,9 +1680,52 @@ class Guides:
|
|
1570
1680
|
)
|
1571
1681
|
if element:
|
1572
1682
|
if axis == "vertical":
|
1573
|
-
|
1683
|
+
if align == "left":
|
1684
|
+
guides_coords.append(element.x0)
|
1685
|
+
elif align == "right":
|
1686
|
+
guides_coords.append(element.x1)
|
1687
|
+
elif align == "center":
|
1688
|
+
guides_coords.append((element.x0 + element.x1) / 2)
|
1689
|
+
elif align == "between":
|
1690
|
+
# For between, collect left edges for processing later
|
1691
|
+
guides_coords.append(element.x0)
|
1574
1692
|
else: # horizontal
|
1575
|
-
|
1693
|
+
if align == "left": # top for horizontal
|
1694
|
+
guides_coords.append(element.top)
|
1695
|
+
elif align == "right": # bottom for horizontal
|
1696
|
+
guides_coords.append(element.bottom)
|
1697
|
+
elif align == "center":
|
1698
|
+
guides_coords.append((element.top + element.bottom) / 2)
|
1699
|
+
elif align == "between":
|
1700
|
+
# For between, collect top edges for processing later
|
1701
|
+
guides_coords.append(element.top)
|
1702
|
+
|
1703
|
+
# Handle 'between' alignment - find midpoints between adjacent markers
|
1704
|
+
if align == "between" and len(guides_coords) >= 2:
|
1705
|
+
# We need to get the right and left edges of each marker
|
1706
|
+
marker_bounds = []
|
1707
|
+
|
1708
|
+
if elements_to_process:
|
1709
|
+
# Use elements directly
|
1710
|
+
for element in elements_to_process:
|
1711
|
+
if axis == "vertical":
|
1712
|
+
marker_bounds.append((element.x0, element.x1))
|
1713
|
+
else: # horizontal
|
1714
|
+
marker_bounds.append((element.top, element.bottom))
|
1715
|
+
else:
|
1716
|
+
# Fall back to text search
|
1717
|
+
if "marker_texts" not in locals():
|
1718
|
+
marker_texts = _normalize_markers(markers, obj)
|
1719
|
+
for marker in marker_texts:
|
1720
|
+
if hasattr(obj, "find"):
|
1721
|
+
element = obj.find(
|
1722
|
+
f'text:contains("{marker}")', apply_exclusions=apply_exclusions
|
1723
|
+
)
|
1724
|
+
if element:
|
1725
|
+
if axis == "vertical":
|
1726
|
+
marker_bounds.append((element.x0, element.x1))
|
1727
|
+
else: # horizontal
|
1728
|
+
marker_bounds.append((element.top, element.bottom))
|
1576
1729
|
|
1577
1730
|
# Sort markers by their left edge (or top edge for horizontal)
|
1578
1731
|
marker_bounds.sort(key=lambda x: x[0])
|
@@ -92,6 +92,16 @@ class HighlightRenderer:
|
|
92
92
|
|
93
93
|
def _draw_highlights(self):
|
94
94
|
"""Draws all highlight shapes, borders, vertices, and attributes."""
|
95
|
+
# Get the pdfplumber page offset for coordinate translation
|
96
|
+
page_offset_x = 0
|
97
|
+
page_offset_y = 0
|
98
|
+
|
99
|
+
if hasattr(self.page, "_page") and hasattr(self.page._page, "bbox"):
|
100
|
+
# PDFPlumber page bbox might have negative offsets
|
101
|
+
page_offset_x = -self.page._page.bbox[0]
|
102
|
+
page_offset_y = -self.page._page.bbox[1]
|
103
|
+
logger.debug(f"Applying highlight offset: x={page_offset_x}, y={page_offset_y}")
|
104
|
+
|
95
105
|
for highlight in self.highlights:
|
96
106
|
# Create a transparent overlay for this single highlight
|
97
107
|
overlay = Image.new("RGBA", self.base_image.size, (0, 0, 0, 0))
|
@@ -101,7 +111,11 @@ class HighlightRenderer:
|
|
101
111
|
|
102
112
|
if highlight.is_polygon:
|
103
113
|
scaled_polygon = [
|
104
|
-
(
|
114
|
+
(
|
115
|
+
(p[0] + page_offset_x) * self.scale_factor,
|
116
|
+
(p[1] + page_offset_y) * self.scale_factor,
|
117
|
+
)
|
118
|
+
for p in highlight.polygon
|
105
119
|
]
|
106
120
|
# Draw polygon fill and border
|
107
121
|
draw.polygon(
|
@@ -117,11 +131,16 @@ class HighlightRenderer:
|
|
117
131
|
else: # Rectangle
|
118
132
|
x0, top, x1, bottom = highlight.bbox
|
119
133
|
x0_s, top_s, x1_s, bottom_s = (
|
120
|
-
x0 * self.scale_factor,
|
121
|
-
top * self.scale_factor,
|
122
|
-
x1 * self.scale_factor,
|
123
|
-
bottom * self.scale_factor,
|
134
|
+
(x0 + page_offset_x) * self.scale_factor,
|
135
|
+
(top + page_offset_y) * self.scale_factor,
|
136
|
+
(x1 + page_offset_x) * self.scale_factor,
|
137
|
+
(bottom + page_offset_y) * self.scale_factor,
|
124
138
|
)
|
139
|
+
logger.debug(f"Original bbox: ({x0}, {top}, {x1}, {bottom})")
|
140
|
+
logger.debug(
|
141
|
+
f"Offset bbox: ({x0 + page_offset_x}, {top + page_offset_y}, {x1 + page_offset_x}, {bottom + page_offset_y})"
|
142
|
+
)
|
143
|
+
logger.debug(f"Scaled bbox: ({x0_s}, {top_s}, {x1_s}, {bottom_s})")
|
125
144
|
scaled_bbox = [x0_s, top_s, x1_s, bottom_s]
|
126
145
|
# Draw rectangle fill and border
|
127
146
|
draw.rectangle(
|
@@ -1482,11 +1501,22 @@ class HighlightingService:
|
|
1482
1501
|
offset_x = crop_offset[0] * scale_factor
|
1483
1502
|
offset_y = crop_offset[1] * scale_factor
|
1484
1503
|
|
1504
|
+
# Add pdfplumber page offset for coordinate translation
|
1505
|
+
page_offset_x = 0
|
1506
|
+
page_offset_y = 0
|
1507
|
+
if hasattr(page, "_page") and hasattr(page._page, "bbox"):
|
1508
|
+
# PDFPlumber page bbox might have negative offsets
|
1509
|
+
page_offset_x = -page._page.bbox[0]
|
1510
|
+
page_offset_y = -page._page.bbox[1]
|
1511
|
+
|
1485
1512
|
# Draw the highlight
|
1486
1513
|
if polygon:
|
1487
1514
|
# Scale polygon points and apply offset
|
1488
1515
|
scaled_polygon = [
|
1489
|
-
(
|
1516
|
+
(
|
1517
|
+
(p[0] + page_offset_x) * scale_factor - offset_x,
|
1518
|
+
(p[1] + page_offset_y) * scale_factor - offset_y,
|
1519
|
+
)
|
1490
1520
|
for p in polygon
|
1491
1521
|
]
|
1492
1522
|
draw.polygon(
|
@@ -1496,10 +1526,10 @@ class HighlightingService:
|
|
1496
1526
|
# Scale bbox and apply offset
|
1497
1527
|
x0, y0, x1, y1 = bbox
|
1498
1528
|
scaled_bbox = [
|
1499
|
-
x0 * scale_factor - offset_x,
|
1500
|
-
y0 * scale_factor - offset_y,
|
1501
|
-
x1 * scale_factor - offset_x,
|
1502
|
-
y1 * scale_factor - offset_y,
|
1529
|
+
(x0 + page_offset_x) * scale_factor - offset_x,
|
1530
|
+
(y0 + page_offset_y) * scale_factor - offset_y,
|
1531
|
+
(x1 + page_offset_x) * scale_factor - offset_x,
|
1532
|
+
(y1 + page_offset_y) * scale_factor - offset_y,
|
1503
1533
|
]
|
1504
1534
|
draw.rectangle(
|
1505
1535
|
scaled_bbox, fill=color, outline=(color[0], color[1], color[2], BORDER_ALPHA)
|
natural_pdf/core/page.py
CHANGED
@@ -815,11 +815,38 @@ class Page(
|
|
815
815
|
if debug:
|
816
816
|
print(f" ✗ Empty iterable returned from callable '{label}'")
|
817
817
|
elif region_result:
|
818
|
-
|
819
|
-
|
820
|
-
|
821
|
-
if
|
822
|
-
|
818
|
+
# Check if it's a single Element that can be converted to a Region
|
819
|
+
from natural_pdf.elements.base import Element
|
820
|
+
|
821
|
+
if isinstance(region_result, Element) or (
|
822
|
+
hasattr(region_result, "bbox") and hasattr(region_result, "expand")
|
823
|
+
):
|
824
|
+
try:
|
825
|
+
# Convert Element to Region using expand()
|
826
|
+
expanded_region = region_result.expand()
|
827
|
+
if isinstance(expanded_region, Region):
|
828
|
+
expanded_region.label = label
|
829
|
+
regions.append(expanded_region)
|
830
|
+
if debug:
|
831
|
+
print(
|
832
|
+
f" ✓ Converted Element to Region from callable '{label}': {expanded_region}"
|
833
|
+
)
|
834
|
+
else:
|
835
|
+
if debug:
|
836
|
+
print(
|
837
|
+
f" ✗ Element.expand() did not return a Region: {type(expanded_region)}"
|
838
|
+
)
|
839
|
+
except Exception as e:
|
840
|
+
if debug:
|
841
|
+
print(f" ✗ Failed to convert Element to Region: {e}")
|
842
|
+
else:
|
843
|
+
logger.warning(
|
844
|
+
f"Callable exclusion '{exclusion_label}' returned non-Region object: {type(region_result)}. Skipping."
|
845
|
+
)
|
846
|
+
if debug:
|
847
|
+
print(
|
848
|
+
f" ✗ Callable returned non-Region/None: {type(region_result)}"
|
849
|
+
)
|
823
850
|
else:
|
824
851
|
if debug:
|
825
852
|
print(
|
@@ -839,6 +866,27 @@ class Page(
|
|
839
866
|
if debug:
|
840
867
|
print(f" - Added direct region '{label}': {exclusion_item}")
|
841
868
|
|
869
|
+
# Process direct Element objects - convert to Region
|
870
|
+
elif hasattr(exclusion_item, "bbox") and hasattr(exclusion_item, "expand"):
|
871
|
+
try:
|
872
|
+
# Convert Element to Region using expand()
|
873
|
+
expanded_region = exclusion_item.expand()
|
874
|
+
if isinstance(expanded_region, Region):
|
875
|
+
expanded_region.label = label
|
876
|
+
regions.append(expanded_region)
|
877
|
+
if debug:
|
878
|
+
print(
|
879
|
+
f" - Converted direct Element to Region '{label}': {expanded_region}"
|
880
|
+
)
|
881
|
+
else:
|
882
|
+
if debug:
|
883
|
+
print(
|
884
|
+
f" - Element.expand() did not return a Region: {type(expanded_region)}"
|
885
|
+
)
|
886
|
+
except Exception as e:
|
887
|
+
if debug:
|
888
|
+
print(f" - Failed to convert Element to Region: {e}")
|
889
|
+
|
842
890
|
# Process string selectors (from PDF-level exclusions)
|
843
891
|
elif isinstance(exclusion_item, str):
|
844
892
|
selector_str = exclusion_item
|
@@ -1081,7 +1129,7 @@ class Page(
|
|
1081
1129
|
) # _apply_selector doesn't filter
|
1082
1130
|
|
1083
1131
|
# Filter the results based on exclusions if requested
|
1084
|
-
if apply_exclusions and
|
1132
|
+
if apply_exclusions and results_collection:
|
1085
1133
|
filtered_elements = self._filter_elements_by_exclusions(results_collection.elements)
|
1086
1134
|
# Return the first element from the filtered list
|
1087
1135
|
return filtered_elements[0] if filtered_elements else None
|
@@ -1176,7 +1224,7 @@ class Page(
|
|
1176
1224
|
) # _apply_selector doesn't filter
|
1177
1225
|
|
1178
1226
|
# Filter the results based on exclusions if requested
|
1179
|
-
if apply_exclusions and
|
1227
|
+
if apply_exclusions and results_collection:
|
1180
1228
|
filtered_elements = self._filter_elements_by_exclusions(results_collection.elements)
|
1181
1229
|
return ElementCollection(filtered_elements)
|
1182
1230
|
else:
|
@@ -1548,7 +1596,7 @@ class Page(
|
|
1548
1596
|
all_elements = self._element_mgr.get_all_elements()
|
1549
1597
|
|
1550
1598
|
# Apply exclusions if requested
|
1551
|
-
if apply_exclusions
|
1599
|
+
if apply_exclusions:
|
1552
1600
|
return self._filter_elements_by_exclusions(
|
1553
1601
|
all_elements, debug_exclusions=debug_exclusions
|
1554
1602
|
)
|
natural_pdf/elements/base.py
CHANGED
@@ -106,6 +106,7 @@ class DirectionalMixin:
|
|
106
106
|
include_source: bool = False,
|
107
107
|
until: Optional[str] = None,
|
108
108
|
include_endpoint: bool = True,
|
109
|
+
offset: float = 0.1,
|
109
110
|
**kwargs,
|
110
111
|
) -> "Region":
|
111
112
|
"""
|
@@ -118,6 +119,7 @@ class DirectionalMixin:
|
|
118
119
|
include_source: Whether to include this element/region's area in the result
|
119
120
|
until: Optional selector string to specify a boundary element
|
120
121
|
include_endpoint: Whether to include the boundary element found by 'until'
|
122
|
+
offset: Pixel offset when excluding source/endpoint (default: 0.1)
|
121
123
|
**kwargs: Additional parameters for the 'until' selector search
|
122
124
|
|
123
125
|
Returns:
|
@@ -127,7 +129,7 @@ class DirectionalMixin:
|
|
127
129
|
|
128
130
|
is_horizontal = direction in ("left", "right")
|
129
131
|
is_positive = direction in ("right", "below") # right/below are positive directions
|
130
|
-
pixel_offset =
|
132
|
+
pixel_offset = offset # Use provided offset for excluding elements/endpoints
|
131
133
|
|
132
134
|
# 1. Determine initial boundaries based on direction and include_source
|
133
135
|
if is_horizontal:
|
@@ -260,6 +262,7 @@ class DirectionalMixin:
|
|
260
262
|
include_source: bool = False,
|
261
263
|
until: Optional[str] = None,
|
262
264
|
include_endpoint: bool = True,
|
265
|
+
offset: float = 0.1,
|
263
266
|
**kwargs,
|
264
267
|
) -> "Region":
|
265
268
|
"""
|
@@ -271,6 +274,7 @@ class DirectionalMixin:
|
|
271
274
|
include_source: Whether to include this element/region in the result (default: False)
|
272
275
|
until: Optional selector string to specify an upper boundary element
|
273
276
|
include_endpoint: Whether to include the boundary element in the region (default: True)
|
277
|
+
offset: Pixel offset when excluding source/endpoint (default: 0.1)
|
274
278
|
**kwargs: Additional parameters
|
275
279
|
|
276
280
|
Returns:
|
@@ -295,6 +299,7 @@ class DirectionalMixin:
|
|
295
299
|
include_source=include_source,
|
296
300
|
until=until,
|
297
301
|
include_endpoint=include_endpoint,
|
302
|
+
offset=offset,
|
298
303
|
**kwargs,
|
299
304
|
)
|
300
305
|
|
@@ -305,6 +310,7 @@ class DirectionalMixin:
|
|
305
310
|
include_source: bool = False,
|
306
311
|
until: Optional[str] = None,
|
307
312
|
include_endpoint: bool = True,
|
313
|
+
offset: float = 0.1,
|
308
314
|
**kwargs,
|
309
315
|
) -> "Region":
|
310
316
|
"""
|
@@ -316,6 +322,7 @@ class DirectionalMixin:
|
|
316
322
|
include_source: Whether to include this element/region in the result (default: False)
|
317
323
|
until: Optional selector string to specify a lower boundary element
|
318
324
|
include_endpoint: Whether to include the boundary element in the region (default: True)
|
325
|
+
offset: Pixel offset when excluding source/endpoint (default: 0.1)
|
319
326
|
**kwargs: Additional parameters
|
320
327
|
|
321
328
|
Returns:
|
@@ -340,6 +347,7 @@ class DirectionalMixin:
|
|
340
347
|
include_source=include_source,
|
341
348
|
until=until,
|
342
349
|
include_endpoint=include_endpoint,
|
350
|
+
offset=offset,
|
343
351
|
**kwargs,
|
344
352
|
)
|
345
353
|
|
@@ -350,6 +358,7 @@ class DirectionalMixin:
|
|
350
358
|
include_source: bool = False,
|
351
359
|
until: Optional[str] = None,
|
352
360
|
include_endpoint: bool = True,
|
361
|
+
offset: float = 0.1,
|
353
362
|
**kwargs,
|
354
363
|
) -> "Region":
|
355
364
|
"""
|
@@ -361,6 +370,7 @@ class DirectionalMixin:
|
|
361
370
|
include_source: Whether to include this element/region in the result (default: False)
|
362
371
|
until: Optional selector string to specify a left boundary element
|
363
372
|
include_endpoint: Whether to include the boundary element in the region (default: True)
|
373
|
+
offset: Pixel offset when excluding source/endpoint (default: 0.1)
|
364
374
|
**kwargs: Additional parameters
|
365
375
|
|
366
376
|
Returns:
|
@@ -385,6 +395,7 @@ class DirectionalMixin:
|
|
385
395
|
include_source=include_source,
|
386
396
|
until=until,
|
387
397
|
include_endpoint=include_endpoint,
|
398
|
+
offset=offset,
|
388
399
|
**kwargs,
|
389
400
|
)
|
390
401
|
|
@@ -395,6 +406,7 @@ class DirectionalMixin:
|
|
395
406
|
include_source: bool = False,
|
396
407
|
until: Optional[str] = None,
|
397
408
|
include_endpoint: bool = True,
|
409
|
+
offset: float = 0.1,
|
398
410
|
**kwargs,
|
399
411
|
) -> "Region":
|
400
412
|
"""
|
@@ -406,6 +418,7 @@ class DirectionalMixin:
|
|
406
418
|
include_source: Whether to include this element/region in the result (default: False)
|
407
419
|
until: Optional selector string to specify a right boundary element
|
408
420
|
include_endpoint: Whether to include the boundary element in the region (default: True)
|
421
|
+
offset: Pixel offset when excluding source/endpoint (default: 0.1)
|
409
422
|
**kwargs: Additional parameters
|
410
423
|
|
411
424
|
Returns:
|
@@ -430,6 +443,7 @@ class DirectionalMixin:
|
|
430
443
|
include_source=include_source,
|
431
444
|
until=until,
|
432
445
|
include_endpoint=include_endpoint,
|
446
|
+
offset=offset,
|
433
447
|
**kwargs,
|
434
448
|
)
|
435
449
|
|