natural-pdf 0.2.11__py3-none-any.whl → 0.2.12__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.
@@ -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: Literal["left", "right", "center", "between"] = "left",
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
- # Normalize markers for this region
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=marker_texts,
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
- # Normalize markers to list of text strings
316
- marker_texts = _normalize_markers(actual_markers, target_obj)
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=marker_texts,
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: Literal["left", "right", "center", "between"] = "left",
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
- # Normalize markers to list of text strings
1534
- marker_texts = _normalize_markers(markers, obj)
1631
+ # Handle different marker types
1632
+ elements_to_process = []
1535
1633
 
1536
- # Find each marker and determine guide position
1537
- for marker in marker_texts:
1538
- if hasattr(obj, "find"):
1539
- element = obj.find(f'text:contains("{marker}")', apply_exclusions=apply_exclusions)
1540
- if element:
1541
- if axis == "vertical":
1542
- if align == "left":
1543
- guides_coords.append(element.x0)
1544
- elif align == "right":
1545
- guides_coords.append(element.x1)
1546
- elif align == "center":
1547
- guides_coords.append((element.x0 + element.x1) / 2)
1548
- elif align == "between":
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
- # Handle 'between' alignment - find midpoints between adjacent markers
1563
- if align == "between" and len(guides_coords) >= 2:
1564
- # We need to get the right and left edges of each marker
1565
- marker_bounds = []
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
- marker_bounds.append((element.x0, element.x1))
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
- marker_bounds.append((element.top, element.bottom))
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])
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
- logger.warning(
819
- f"Callable exclusion '{exclusion_label}' returned non-Region object: {type(region_result)}. Skipping."
820
- )
821
- if debug:
822
- print(f" Callable returned non-Region/None: {type(region_result)}")
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 self._exclusions and results_collection:
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 self._exclusions and results_collection:
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 and self._exclusions:
1599
+ if apply_exclusions:
1552
1600
  return self._filter_elements_by_exclusions(
1553
1601
  all_elements, debug_exclusions=debug_exclusions
1554
1602
  )
@@ -1270,7 +1270,8 @@ class Region(
1270
1270
  # 3. Get Relevant Exclusions (overlapping this region)
1271
1271
  apply_exclusions_flag = kwargs.get("apply_exclusions", apply_exclusions)
1272
1272
  exclusion_regions = []
1273
- if apply_exclusions_flag and self._page._exclusions:
1273
+ if apply_exclusions_flag:
1274
+ # Always call _get_exclusion_regions to get both page and PDF level exclusions
1274
1275
  all_page_exclusions = self._page._get_exclusion_regions(
1275
1276
  include_callable=True, debug=debug
1276
1277
  )
@@ -1281,10 +1282,11 @@ class Region(
1281
1282
  exclusion_regions = overlapping_exclusions
1282
1283
  if debug:
1283
1284
  logger.debug(
1284
- f"Region {self.bbox}: Applying {len(exclusion_regions)} overlapping exclusions."
1285
+ f"Region {self.bbox}: Found {len(all_page_exclusions)} total exclusions, "
1286
+ f"{len(exclusion_regions)} overlapping this region."
1285
1287
  )
1286
1288
  elif debug:
1287
- logger.debug(f"Region {self.bbox}: Not applying exclusions.")
1289
+ logger.debug(f"Region {self.bbox}: Not applying exclusions (apply_exclusions=False).")
1288
1290
 
1289
1291
  # 4. Spatially Filter Characters using Utility
1290
1292
  # Pass self as the target_region for precise polygon checks etc.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: natural-pdf
3
- Version: 0.2.11
3
+ Version: 0.2.12
4
4
  Summary: A more intuitive interface for working with PDFs
5
5
  Author-email: Jonathan Soma <jonathan.soma@gmail.com>
6
6
  License-Expression: MIT
@@ -2,7 +2,7 @@ natural_pdf/__init__.py,sha256=N4pR0LbuPEnUYFZqbdVqc_FGKldgwPQc1wjJhYKTBBM,3417
2
2
  natural_pdf/cli.py,sha256=0zO9ZoRiP8JmyGBaVavrMATnvbARWTl7WD2PEefu9BM,4061
3
3
  natural_pdf/text_mixin.py,sha256=eFCiHj6Okcw3aum4955BepcI2NPRalkf9UFFVTc_H30,4012
4
4
  natural_pdf/analyzers/__init__.py,sha256=3XGoNq3OgiVkZP7tOdeP5XVUl7fDgyztdA8DlOcMLXg,1138
5
- natural_pdf/analyzers/guides.py,sha256=GQZHjl7wUpaxAKRpv4cyQf1SJuccMSjpngBKFCKNHK4,181795
5
+ natural_pdf/analyzers/guides.py,sha256=B2_Etb0o-lOku-FQw-T1Fo1qxbcAXT4FB0hdp-5kXRs,188171
6
6
  natural_pdf/analyzers/shape_detection_mixin.py,sha256=mgpyJ4jIulz9l9HCqThabJIsLSrXh9BB2AmLxUoHmw0,62584
7
7
  natural_pdf/analyzers/text_options.py,sha256=qEkDaYWla0rIM_gszEOsu52q7C_dAfV81P2HLJZM2sw,3333
8
8
  natural_pdf/analyzers/text_structure.py,sha256=3WWusi-BI0krUnJxB05DD6XmKj5qRNvQBqH7zOQGm1M,28451
@@ -27,7 +27,7 @@ natural_pdf/collections/mixins.py,sha256=Se2C5AcpP9B5E0d0pIrey6-f_P32tAXTK4M7666
27
27
  natural_pdf/core/__init__.py,sha256=QC8H4M3KbXwMFiQORZ0pdPlzx1Ix6oKKQSS7Ib2KEaA,38
28
28
  natural_pdf/core/element_manager.py,sha256=KPuKM7SstfErTkRnGq4vrgE0Tv8iazN13Jp7yAXGKso,55575
29
29
  natural_pdf/core/highlighting_service.py,sha256=7on8nErhi50CEH2L4XzGIZ6tIqZtMzmmFlp-2lmwnYE,68856
30
- natural_pdf/core/page.py,sha256=XmXii652iM-JVKgzpbKQ8f59U0TvDLD5iAfdtx92gis,152675
30
+ natural_pdf/core/page.py,sha256=Pid5hqVjcyX-gcCzxCJ62k6AQhNbUMNM_5QmEcylIjM,155264
31
31
  natural_pdf/core/page_collection.py,sha256=IjdFq9q0D0P6ZKWInf0H25rLzxfMb7RsUXucogkhNkU,63169
32
32
  natural_pdf/core/page_groupby.py,sha256=V2e_RNlHaasUzYm2h2vNJI7_aV_fl3_pg7kU3F2j0z8,8218
33
33
  natural_pdf/core/pdf.py,sha256=ovdeu9TRPnVYyMltD7QpcdcFYBLZFXh3LlfC5ifj6RY,104227
@@ -44,7 +44,7 @@ natural_pdf/elements/element_collection.py,sha256=idM_BUWEfbCJ5Sq0Ae_KfbVHy8TdkN
44
44
  natural_pdf/elements/image.py,sha256=zu-P2Y8fRoEXf6IeZU0EYRWsgZ6I_a5vy1FA3VXTGkQ,1424
45
45
  natural_pdf/elements/line.py,sha256=TFn7KXjPT_jUQyQyabU0F7XYU4dC-qadwodJMZF4DCU,3844
46
46
  natural_pdf/elements/rect.py,sha256=0lNkVkPkvbRbrFED856RXoUcTcDkeeOIs5xldKGAQT8,3324
47
- natural_pdf/elements/region.py,sha256=hCpbKg0R5TGfWEskZ6P-o_ZXPKhU4keaYjWIVX0Y7F4,165244
47
+ natural_pdf/elements/region.py,sha256=HF6KzeuudO9upVLIrPsp3omcziLcILE3nnzl1a-LvK0,165400
48
48
  natural_pdf/elements/text.py,sha256=829uSJv9E-8cC6T6iR_Va7Xtv54pJoyRN78fq4NN1d4,20687
49
49
  natural_pdf/export/mixin.py,sha256=L1q3MIEFWuvie4j4_EmW7GT3NerbZ1as0XMUoqTS7gM,5083
50
50
  natural_pdf/exporters/__init__.py,sha256=QffoARekR6WzXEd05oxOytly4qPdBizuIF-SUkeFpig,643
@@ -107,12 +107,32 @@ natural_pdf/vision/results.py,sha256=F2zXG3MVZIpOUvPkJHotOq6-9rFz68BaO_8pnSndlOs
107
107
  natural_pdf/vision/similarity.py,sha256=YH8legN-t9uf1b_XULi4JLNDaRfPNKQwU1FZ4Qu08jY,11740
108
108
  natural_pdf/widgets/__init__.py,sha256=QTVaUmsw__FCweFYZebwPssQxxUFUMd0wpm_cUbGZJY,181
109
109
  natural_pdf/widgets/viewer.py,sha256=KW3JogdR2TMg2ECUMYp8hwd060hfg8EsYBWxb5IEzBY,24942
110
- natural_pdf-0.2.11.dist-info/licenses/LICENSE,sha256=9zfwINwJlarbDmdh6iJV4QUG54QSJlSAUcnC1YiC_Ns,1074
110
+ natural_pdf-0.2.12.dist-info/licenses/LICENSE,sha256=9zfwINwJlarbDmdh6iJV4QUG54QSJlSAUcnC1YiC_Ns,1074
111
111
  optimization/memory_comparison.py,sha256=0i_foFSRmppj-fY069qjwH36s_zkx-1L2ASAAlepWzA,6541
112
112
  optimization/pdf_analyzer.py,sha256=HjrmTgu2qchxPeDckc5kjgxppGwd40UESrYS9Myj7pY,19352
113
113
  optimization/performance_analysis.py,sha256=JBXnR9hc7Ix7YCnt3EJPSpsyqIUgKsc7GEffQ_TDCBk,13033
114
114
  optimization/test_cleanup_methods.py,sha256=PmLOL4MRgvV0j_DW9W1TS8MsGGgu57QCuq6_5y7zK3s,6209
115
115
  optimization/test_memory_fix.py,sha256=A3knK74fNhvHknDbLhbTmA276x1ifl-3ivJ_7BhVSTI,6170
116
+ temp/debug_cell_extraction.py,sha256=nE0Z470P40v8xZfWO1V3qgNaejs_pernEQaUOFeOJ1U,1527
117
+ temp/debug_exclusion_overlap.py,sha256=RptJXwqBXy5gsvMF037KEx1o2QgjwEDkMB6TD5aJdqA,1644
118
+ temp/debug_exclusions_guides.py,sha256=s8siep9te1KRJ2j0vH1tvDQnBlz7PKbHeCiYMrZL8jE,2096
119
+ temp/debug_extra_guide.py,sha256=95Tim-YnmAR4kICw2XDKVDvlW5WsjK_51cv5-EV11rc,1236
120
+ temp/debug_outer_boundaries.py,sha256=uJUJwojTxOU4VtbGUouuhV65IYzS6NDIVKxnS7o64nU,1456
121
+ temp/debug_st_search.py,sha256=F4c_mUVi_d5AKaKIpQ0AnW1amDqAwALoQQj7wZj--J0,1021
122
+ temp/fix_page_exclusions.py,sha256=YIj62zF38TdoBARAuSIvEbetl_JfXG-mp4v9p355qmo,1358
123
+ temp/test_exclusion_with_debug.py,sha256=CScxHvb43KrB5dzXuTOhuzjcBXZBdfYB5ygiKkEW26g,1393
124
+ temp/test_find_exclusions_fix.py,sha256=1l5aEqnElcl3kiykdtmJFlVxQ1xMKGm1UckGYEQg--c,2103
125
+ temp/test_find_exclusions_fix_no_recursion.py,sha256=qZspTBwxunRM93N_-fZ2fR5Lodj0ArQX3h10HlTXhfc,3592
126
+ temp/test_fix_real_pdf.py,sha256=uuylxmpeAEbIix9wjl0Gri1sZlN61dBWTq6ZCyfvzF8,1454
127
+ temp/test_fix_working.py,sha256=-Ryre1rXYA2EG_lmPZGYEGi8yz0slhHEXPJMYexZW84,1750
128
+ temp/test_fixed_pdf_exclusions.py,sha256=Q5zxooKDvtTXo-dDsx3nsQw1ZVHX3TW47iZ_dXpFdrY,2168
129
+ temp/test_horizontal_top_bottom.py,sha256=Mb3tjt9Z3wOTpzFOgK7i0K-j-_ynNh4vDu2x1L3nu-s,2163
130
+ temp/test_marker_order.py,sha256=TFZkMxRiNoZGVcdDivYnkIDNvwHaiyKUdYoy2rTTIiI,1417
131
+ temp/test_original_exclusions_now_work.py,sha256=G6LmaF-P9Qhj0j4lT_4ncfCddllfP6L8F_x2prUBr9w,1904
132
+ temp/test_pdf_exclusions_with_guides.py,sha256=QaMl0frgKC8kCPQ2BUI8kqyvqsIjQPXKV_St1rK3zxg,2754
133
+ temp/test_region_exclusions_detailed.py,sha256=EftdW3JY3JH_LX5QlWKt-4drM-joPggK2fKUZRXVTMA,814
134
+ temp/test_stripes_real_pdf.py,sha256=FIvDoJrnuioOMw1A0aTCCfZLeg99lusfe0Fb0MiqnhQ,2618
135
+ temp/test_vertical_stripes.py,sha256=Yf3TJfb_faqAFzlgb7i5u6dDHjF4UMSHIGM99vangRk,1877
116
136
  tools/bad_pdf_eval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
117
137
  tools/bad_pdf_eval/analyser.py,sha256=oqSTo3NLyignp_XdCO9_SRCUUXMU8lfgDavKYZYNxws,13690
118
138
  tools/bad_pdf_eval/collate_summaries.py,sha256=L_YsdiqmwGIHYWTVJqo6gyazyn3GIQgpfGGKk8uwckk,5159
@@ -124,8 +144,8 @@ tools/bad_pdf_eval/llm_enrich.py,sha256=mCh4KGi1HmIkzGjj5rrHz1Osd7sEX1IZ_FW08H1t
124
144
  tools/bad_pdf_eval/llm_enrich_with_retry.py,sha256=XUtPF1hUvqd3frDXT0wDTXoonuAivhjM5vgFdZ-tm0A,9373
125
145
  tools/bad_pdf_eval/reporter.py,sha256=e1g__mkSB4q02p3mGWOwMhvFs7F2HJosNBxup0-LkyU,400
126
146
  tools/bad_pdf_eval/utils.py,sha256=hR95XQ7qf7Cu6BdyX0L7ggGVx-ah5sK0jHWblTJUUic,4896
127
- natural_pdf-0.2.11.dist-info/METADATA,sha256=RBk1DrwdyTY0cJvFdWqfvM2hMd4OY30Lc0BlXopknD4,6960
128
- natural_pdf-0.2.11.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
129
- natural_pdf-0.2.11.dist-info/entry_points.txt,sha256=1R_KMv7g60UBBpRqGfw7bppsMNGdayR-iJlb9ohEk_8,81
130
- natural_pdf-0.2.11.dist-info/top_level.txt,sha256=80t0F2ZeX4vN4Ke5iTflcOk_PN_0USn33ha3X6X86Ik,36
131
- natural_pdf-0.2.11.dist-info/RECORD,,
147
+ natural_pdf-0.2.12.dist-info/METADATA,sha256=jRNM0JxYvPDuqzD63earjbaUwQgXCjPYPLC5pLl49Uk,6960
148
+ natural_pdf-0.2.12.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
149
+ natural_pdf-0.2.12.dist-info/entry_points.txt,sha256=1R_KMv7g60UBBpRqGfw7bppsMNGdayR-iJlb9ohEk_8,81
150
+ natural_pdf-0.2.12.dist-info/top_level.txt,sha256=ZDKhxE_tg508o9BpagsjCGcI8GY4cF_8bg0e0IaLsPI,41
151
+ natural_pdf-0.2.12.dist-info/RECORD,,
@@ -1,4 +1,5 @@
1
1
  natural_pdf
2
2
  optimization
3
+ temp
3
4
  todo
4
5
  tools
@@ -0,0 +1,42 @@
1
+ """Debug cell text extraction with exclusions"""
2
+ from natural_pdf import PDF
3
+ from natural_pdf.analyzers.guides import Guides
4
+
5
+ pdf = PDF("pdfs/m27.pdf")
6
+ page = pdf.pages[0]
7
+
8
+ # Add exclusions
9
+ pdf.add_exclusion(lambda page: page.find(text="PREMISE").above(), label="header")
10
+
11
+ # Check exclusions are registered
12
+ print("Exclusions on page:")
13
+ exclusions = page._get_exclusion_regions(debug=True)
14
+
15
+ # Create guides and build grid
16
+ headers = page.find(text="NUMBER").right(include_source=True).expand(top=3, bottom=3).find_all('text')
17
+ guides = Guides(page)
18
+ guides.vertical.from_content(headers, align='left')
19
+ guides.horizontal.from_stripes()
20
+
21
+ # Build grid and get cells
22
+ grid_result = guides.build_grid(include_outer_boundaries=True)
23
+ cells = grid_result["regions"]["cells"]
24
+
25
+ print(f"\nTotal cells: {len(cells)}")
26
+
27
+ # Check first row cells (these should be in excluded area)
28
+ first_row_cells = [c for c in cells if c.bbox[1] < 90] # y < 90
29
+ print(f"\nFirst row cells: {len(first_row_cells)}")
30
+
31
+ for i, cell in enumerate(first_row_cells[:3]):
32
+ print(f"\nCell {i}:")
33
+ print(f" Bbox: {cell.bbox}")
34
+ print(f" Raw text: {repr(cell.extract_text(apply_exclusions=False))}")
35
+ print(f" With exclusions: {repr(cell.extract_text(apply_exclusions=True))}")
36
+
37
+ # Now test the full table extraction
38
+ print("\n\nFull table extraction:")
39
+ result = guides.extract_table(include_outer_boundaries=True, apply_exclusions=True, header=False)
40
+ df = result.to_df()
41
+ print("\nFirst row of dataframe:")
42
+ print(df.iloc[0].to_dict() if not df.empty else "Empty")
@@ -0,0 +1,43 @@
1
+ """Debug how exclusions work with overlapping regions"""
2
+ from natural_pdf import PDF
3
+ from natural_pdf.analyzers.guides import Guides
4
+
5
+ pdf = PDF("pdfs/m27.pdf")
6
+ page = pdf.pages[0]
7
+
8
+ # Add exclusion
9
+ pdf.add_exclusion(lambda page: page.find(text="PREMISE").above(), label="header")
10
+
11
+ # Get the exclusion region
12
+ exclusions = page._get_exclusion_regions()
13
+ excl_region = exclusions[0]
14
+ print(f"Exclusion region: {excl_region.bbox}")
15
+ print(f"Exclusion bottom: {excl_region.bbox[3]}")
16
+
17
+ # Create a test cell that overlaps the exclusion
18
+ # Cell 1 from before: (32.06, 0.5, 73.18288, 79.53999999999996)
19
+ test_cell = page.region(32.06, 0.5, 73.18288, 79.53999999999996)
20
+
21
+ print(f"\nTest cell: {test_cell.bbox}")
22
+ print(f"Cell overlaps exclusion: top={test_cell.bbox[1]} < excl_bottom={excl_region.bbox[3]}")
23
+
24
+ # Extract text from different y-ranges
25
+ print("\nText in different parts of the cell:")
26
+
27
+ # Part above exclusion line (should be empty)
28
+ upper_part = page.region(32.06, 0.5, 73.18288, 59.12)
29
+ print(f"Upper part (0.5 to 59.12): '{upper_part.extract_text(apply_exclusions=True)}'")
30
+
31
+ # Part below exclusion line (should have text)
32
+ lower_part = page.region(32.06, 59.12, 73.18288, 79.54)
33
+ print(f"Lower part (59.12 to 79.54): '{lower_part.extract_text()}'")
34
+
35
+ # The whole cell
36
+ print(f"Whole cell with exclusions: '{test_cell.extract_text(apply_exclusions=True)}'")
37
+ print(f"Whole cell without exclusions: '{test_cell.extract_text(apply_exclusions=False)}'")
38
+
39
+ # Check what text elements are in this region
40
+ print("\nText elements in cell:")
41
+ cell_texts = test_cell.find_all('text')
42
+ for t in cell_texts[:5]:
43
+ print(f" '{t.text}' at y={t.top:.2f}-{t.bottom:.2f}")