natural-pdf 0.2.2__py3-none-any.whl → 0.2.4__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/collections/mixins.py +16 -3
- natural_pdf/core/highlighting_service.py +25 -1
- natural_pdf/core/page.py +5 -3
- natural_pdf/core/page_collection.py +14 -14
- natural_pdf/core/pdf.py +4 -1
- natural_pdf/core/pdf_collection.py +131 -4
- natural_pdf/core/render_spec.py +46 -2
- natural_pdf/elements/base.py +66 -28
- natural_pdf/elements/element_collection.py +10 -10
- natural_pdf/elements/region.py +29 -27
- natural_pdf/vision/__init__.py +7 -0
- natural_pdf/vision/mixin.py +209 -0
- natural_pdf/vision/results.py +146 -0
- natural_pdf/vision/similarity.py +321 -0
- {natural_pdf-0.2.2.dist-info → natural_pdf-0.2.4.dist-info}/METADATA +1 -1
- {natural_pdf-0.2.2.dist-info → natural_pdf-0.2.4.dist-info}/RECORD +20 -16
- {natural_pdf-0.2.2.dist-info → natural_pdf-0.2.4.dist-info}/WHEEL +0 -0
- {natural_pdf-0.2.2.dist-info → natural_pdf-0.2.4.dist-info}/entry_points.txt +0 -0
- {natural_pdf-0.2.2.dist-info → natural_pdf-0.2.4.dist-info}/licenses/LICENSE +0 -0
- {natural_pdf-0.2.2.dist-info → natural_pdf-0.2.4.dist-info}/top_level.txt +0 -0
@@ -29,9 +29,22 @@ class DirectionalCollectionMixin:
|
|
29
29
|
"""Find regions to the right of all elements in this collection."""
|
30
30
|
return self.apply(lambda element: element.right(**kwargs))
|
31
31
|
|
32
|
-
def expand(self, **kwargs) -> "ElementCollection":
|
33
|
-
"""Expand all elements in this collection.
|
34
|
-
|
32
|
+
def expand(self, *args, **kwargs) -> "ElementCollection":
|
33
|
+
"""Expand all elements in this collection.
|
34
|
+
|
35
|
+
Args:
|
36
|
+
*args: If a single positional argument is provided, expands all elements
|
37
|
+
by that amount in all directions.
|
38
|
+
**kwargs: Keyword arguments for directional expansion (left, right, top, bottom, etc.)
|
39
|
+
|
40
|
+
Examples:
|
41
|
+
# Expand all elements by 5 pixels in all directions
|
42
|
+
collection.expand(5)
|
43
|
+
|
44
|
+
# Expand with different amounts in each direction
|
45
|
+
collection.expand(left=10, right=5, top=3, bottom=7)
|
46
|
+
"""
|
47
|
+
return self.apply(lambda element: element.expand(*args, **kwargs))
|
35
48
|
|
36
49
|
|
37
50
|
class ApplyMixin:
|
@@ -335,6 +335,7 @@ class HighlightContext:
|
|
335
335
|
self.show_on_exit = show_on_exit
|
336
336
|
self.highlight_groups = []
|
337
337
|
self._color_manager = ColorManager()
|
338
|
+
self._exit_image = None # Store image for Jupyter display
|
338
339
|
|
339
340
|
def add(
|
340
341
|
self,
|
@@ -421,6 +422,11 @@ class HighlightContext:
|
|
421
422
|
)
|
422
423
|
return None
|
423
424
|
|
425
|
+
@property
|
426
|
+
def image(self) -> Optional[Image.Image]:
|
427
|
+
"""Get the last generated image (useful after context exit)."""
|
428
|
+
return self._exit_image
|
429
|
+
|
424
430
|
def __enter__(self) -> "HighlightContext":
|
425
431
|
"""Enter the context."""
|
426
432
|
return self
|
@@ -428,7 +434,25 @@ class HighlightContext:
|
|
428
434
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
429
435
|
"""Exit the context, optionally showing highlights."""
|
430
436
|
if self.show_on_exit and not exc_type:
|
431
|
-
self.show()
|
437
|
+
self._exit_image = self.show()
|
438
|
+
|
439
|
+
# Check if we're in a Jupyter/IPython environment
|
440
|
+
try:
|
441
|
+
# Try to get IPython instance
|
442
|
+
from IPython import get_ipython
|
443
|
+
|
444
|
+
ipython = get_ipython()
|
445
|
+
if ipython is not None:
|
446
|
+
# We're in IPython/Jupyter
|
447
|
+
from IPython.display import display
|
448
|
+
|
449
|
+
if self._exit_image is not None:
|
450
|
+
display(self._exit_image)
|
451
|
+
except (ImportError, NameError):
|
452
|
+
# Not in Jupyter or IPython not available - that's OK
|
453
|
+
pass
|
454
|
+
|
455
|
+
# __exit__ must return False to not suppress exceptions
|
432
456
|
return False
|
433
457
|
|
434
458
|
|
natural_pdf/core/page.py
CHANGED
@@ -78,6 +78,7 @@ from natural_pdf.utils.locks import pdf_render_lock # Import the lock
|
|
78
78
|
|
79
79
|
# # Import new utils
|
80
80
|
from natural_pdf.utils.text_extraction import filter_chars_spatially, generate_text_layout
|
81
|
+
from natural_pdf.vision.mixin import VisualSearchMixin
|
81
82
|
from natural_pdf.widgets.viewer import _IPYWIDGETS_AVAILABLE, InteractiveViewerWidget
|
82
83
|
|
83
84
|
# --- End Classification Imports --- #
|
@@ -101,6 +102,7 @@ class Page(
|
|
101
102
|
ExtractionMixin,
|
102
103
|
ShapeDetectionMixin,
|
103
104
|
DescribeMixin,
|
105
|
+
VisualSearchMixin,
|
104
106
|
Visualizable,
|
105
107
|
):
|
106
108
|
"""Enhanced Page wrapper built on top of pdfplumber.Page.
|
@@ -1976,7 +1978,7 @@ class Page(
|
|
1976
1978
|
"""Get all line elements on this page."""
|
1977
1979
|
return self._element_mgr.lines
|
1978
1980
|
|
1979
|
-
def
|
1981
|
+
def add_highlight(
|
1980
1982
|
self,
|
1981
1983
|
bbox: Optional[Tuple[float, float, float, float]] = None,
|
1982
1984
|
color: Optional[Union[Tuple, str]] = None,
|
@@ -1987,7 +1989,7 @@ class Page(
|
|
1987
1989
|
existing: str = "append",
|
1988
1990
|
) -> "Page":
|
1989
1991
|
"""
|
1990
|
-
|
1992
|
+
Add a highlight to a bounding box or the entire page.
|
1991
1993
|
Delegates to the central HighlightingService.
|
1992
1994
|
|
1993
1995
|
Args:
|
@@ -2015,7 +2017,7 @@ class Page(
|
|
2015
2017
|
)
|
2016
2018
|
return self
|
2017
2019
|
|
2018
|
-
def
|
2020
|
+
def add_highlight_polygon(
|
2019
2021
|
self,
|
2020
2022
|
polygon: List[Tuple[float, float]],
|
2021
2023
|
color: Optional[Union[Tuple, str]] = None,
|
@@ -259,7 +259,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
259
259
|
self,
|
260
260
|
*,
|
261
261
|
text: str,
|
262
|
-
|
262
|
+
overlap: str = "full",
|
263
263
|
apply_exclusions: bool = True,
|
264
264
|
regex: bool = False,
|
265
265
|
case: bool = True,
|
@@ -271,7 +271,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
271
271
|
self,
|
272
272
|
selector: str,
|
273
273
|
*,
|
274
|
-
|
274
|
+
overlap: str = "full",
|
275
275
|
apply_exclusions: bool = True,
|
276
276
|
regex: bool = False,
|
277
277
|
case: bool = True,
|
@@ -283,7 +283,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
283
283
|
selector: Optional[str] = None,
|
284
284
|
*,
|
285
285
|
text: Optional[str] = None,
|
286
|
-
|
286
|
+
overlap: str = "full",
|
287
287
|
apply_exclusions: bool = True,
|
288
288
|
regex: bool = False,
|
289
289
|
case: bool = True,
|
@@ -297,9 +297,9 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
297
297
|
Args:
|
298
298
|
selector: CSS-like selector string.
|
299
299
|
text: Text content to search for (equivalent to 'text:contains(...)').
|
300
|
-
|
301
|
-
'
|
302
|
-
(default: "
|
300
|
+
overlap: How to determine if elements overlap: 'full' (fully inside),
|
301
|
+
'partial' (any overlap), or 'center' (center point inside).
|
302
|
+
(default: "full")
|
303
303
|
apply_exclusions: Whether to exclude elements in exclusion regions (default: True).
|
304
304
|
regex: Whether to use regex for text search (`selector` or `text`) (default: False).
|
305
305
|
case: Whether to do case-sensitive text search (`selector` or `text`) (default: True).
|
@@ -313,7 +313,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
313
313
|
element = page.find(
|
314
314
|
selector=selector,
|
315
315
|
text=text,
|
316
|
-
|
316
|
+
overlap=overlap,
|
317
317
|
apply_exclusions=apply_exclusions,
|
318
318
|
regex=regex,
|
319
319
|
case=case,
|
@@ -328,7 +328,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
328
328
|
self,
|
329
329
|
*,
|
330
330
|
text: str,
|
331
|
-
|
331
|
+
overlap: str = "full",
|
332
332
|
apply_exclusions: bool = True,
|
333
333
|
regex: bool = False,
|
334
334
|
case: bool = True,
|
@@ -340,7 +340,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
340
340
|
self,
|
341
341
|
selector: str,
|
342
342
|
*,
|
343
|
-
|
343
|
+
overlap: str = "full",
|
344
344
|
apply_exclusions: bool = True,
|
345
345
|
regex: bool = False,
|
346
346
|
case: bool = True,
|
@@ -352,7 +352,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
352
352
|
selector: Optional[str] = None,
|
353
353
|
*,
|
354
354
|
text: Optional[str] = None,
|
355
|
-
|
355
|
+
overlap: str = "full",
|
356
356
|
apply_exclusions: bool = True,
|
357
357
|
regex: bool = False,
|
358
358
|
case: bool = True,
|
@@ -366,9 +366,9 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
366
366
|
Args:
|
367
367
|
selector: CSS-like selector string.
|
368
368
|
text: Text content to search for (equivalent to 'text:contains(...)').
|
369
|
-
|
370
|
-
'
|
371
|
-
(default: "
|
369
|
+
overlap: How to determine if elements overlap: 'full' (fully inside),
|
370
|
+
'partial' (any overlap), or 'center' (center point inside).
|
371
|
+
(default: "full")
|
372
372
|
apply_exclusions: Whether to exclude elements in exclusion regions (default: True).
|
373
373
|
regex: Whether to use regex for text search (`selector` or `text`) (default: False).
|
374
374
|
case: Whether to do case-sensitive text search (`selector` or `text`) (default: True).
|
@@ -383,7 +383,7 @@ class PageCollection(TextMixin, Generic[P], ApplyMixin, ShapeDetectionMixin, Vis
|
|
383
383
|
elements = page.find_all(
|
384
384
|
selector=selector,
|
385
385
|
text=text,
|
386
|
-
|
386
|
+
overlap=overlap,
|
387
387
|
apply_exclusions=apply_exclusions,
|
388
388
|
regex=regex,
|
389
389
|
case=case,
|
natural_pdf/core/pdf.py
CHANGED
@@ -42,6 +42,7 @@ from natural_pdf.ocr import OCRManager, OCROptions
|
|
42
42
|
from natural_pdf.selectors.parser import parse_selector
|
43
43
|
from natural_pdf.text_mixin import TextMixin
|
44
44
|
from natural_pdf.utils.locks import pdf_render_lock
|
45
|
+
from natural_pdf.vision.mixin import VisualSearchMixin
|
45
46
|
|
46
47
|
if TYPE_CHECKING:
|
47
48
|
from natural_pdf.elements.element_collection import ElementCollection
|
@@ -252,7 +253,9 @@ class _LazyPageList(Sequence):
|
|
252
253
|
# --- End Lazy Page List Helper --- #
|
253
254
|
|
254
255
|
|
255
|
-
class PDF(
|
256
|
+
class PDF(
|
257
|
+
TextMixin, ExtractionMixin, ExportMixin, ClassificationMixin, VisualSearchMixin, Visualizable
|
258
|
+
):
|
256
259
|
"""Enhanced PDF wrapper built on top of pdfplumber.
|
257
260
|
|
258
261
|
This class provides a fluent interface for working with PDF documents,
|
@@ -40,6 +40,7 @@ logger = logging.getLogger(__name__)
|
|
40
40
|
from natural_pdf.core.pdf import PDF
|
41
41
|
from natural_pdf.elements.region import Region
|
42
42
|
from natural_pdf.export.mixin import ExportMixin
|
43
|
+
from natural_pdf.vision.mixin import VisualSearchMixin
|
43
44
|
|
44
45
|
# --- Search Imports ---
|
45
46
|
try:
|
@@ -69,8 +70,8 @@ from natural_pdf.search.searchable_mixin import SearchableMixin # Import the ne
|
|
69
70
|
|
70
71
|
|
71
72
|
class PDFCollection(
|
72
|
-
SearchableMixin, ApplyMixin, ExportMixin, ShapeDetectionMixin
|
73
|
-
):
|
73
|
+
SearchableMixin, ApplyMixin, ExportMixin, ShapeDetectionMixin, VisualSearchMixin
|
74
|
+
):
|
74
75
|
def __init__(
|
75
76
|
self,
|
76
77
|
source: Union[str, Iterable[Union[str, "PDF"]]],
|
@@ -258,8 +259,6 @@ class PDFCollection(
|
|
258
259
|
return iter(self._pdfs)
|
259
260
|
|
260
261
|
def __repr__(self) -> str:
|
261
|
-
# Removed search status
|
262
|
-
return f"<PDFCollection(count={len(self._pdfs)})>"
|
263
262
|
return f"<PDFCollection(count={len(self._pdfs)})>"
|
264
263
|
|
265
264
|
@property
|
@@ -267,6 +266,134 @@ class PDFCollection(
|
|
267
266
|
"""Returns the list of PDF objects held by the collection."""
|
268
267
|
return self._pdfs
|
269
268
|
|
269
|
+
def show(self, limit: Optional[int] = 30, per_pdf_limit: Optional[int] = 10, **kwargs):
|
270
|
+
"""
|
271
|
+
Display all PDFs in the collection with labels.
|
272
|
+
|
273
|
+
Each PDF is shown with its pages in a grid layout (6 columns by default),
|
274
|
+
and all PDFs are stacked vertically with labels.
|
275
|
+
|
276
|
+
Args:
|
277
|
+
limit: Maximum total pages to show across all PDFs (default: 30)
|
278
|
+
per_pdf_limit: Maximum pages to show per PDF (default: 10)
|
279
|
+
**kwargs: Additional arguments passed to each PDF's show() method
|
280
|
+
(e.g., columns, exclusions, resolution, etc.)
|
281
|
+
|
282
|
+
Returns:
|
283
|
+
Displayed image in Jupyter or None
|
284
|
+
"""
|
285
|
+
if not self._pdfs:
|
286
|
+
print("Empty collection")
|
287
|
+
return None
|
288
|
+
|
289
|
+
# Import here to avoid circular imports
|
290
|
+
import numpy as np
|
291
|
+
from PIL import Image, ImageDraw, ImageFont
|
292
|
+
|
293
|
+
# Calculate pages per PDF if total limit is set
|
294
|
+
if limit and not per_pdf_limit:
|
295
|
+
per_pdf_limit = max(1, limit // len(self._pdfs))
|
296
|
+
|
297
|
+
# Collect images from each PDF
|
298
|
+
all_images = []
|
299
|
+
total_pages_shown = 0
|
300
|
+
|
301
|
+
for pdf in self._pdfs:
|
302
|
+
if limit and total_pages_shown >= limit:
|
303
|
+
break
|
304
|
+
|
305
|
+
# Calculate limit for this PDF
|
306
|
+
pdf_limit = per_pdf_limit
|
307
|
+
if limit:
|
308
|
+
remaining = limit - total_pages_shown
|
309
|
+
pdf_limit = min(per_pdf_limit or remaining, remaining)
|
310
|
+
|
311
|
+
# Get PDF identifier
|
312
|
+
pdf_name = getattr(pdf, "filename", None) or getattr(pdf, "path", "Unknown")
|
313
|
+
if isinstance(pdf_name, Path):
|
314
|
+
pdf_name = pdf_name.name
|
315
|
+
elif "/" in str(pdf_name):
|
316
|
+
pdf_name = str(pdf_name).split("/")[-1]
|
317
|
+
|
318
|
+
# Render this PDF
|
319
|
+
try:
|
320
|
+
# Get render specs from the PDF
|
321
|
+
render_specs = pdf._get_render_specs(mode="show", max_pages=pdf_limit, **kwargs)
|
322
|
+
|
323
|
+
if not render_specs:
|
324
|
+
continue
|
325
|
+
|
326
|
+
# Get the highlighter and render without displaying
|
327
|
+
highlighter = pdf._get_highlighter()
|
328
|
+
pdf_image = highlighter.unified_render(
|
329
|
+
specs=render_specs,
|
330
|
+
layout="grid" if len(render_specs) > 1 else "single",
|
331
|
+
columns=6,
|
332
|
+
**kwargs,
|
333
|
+
)
|
334
|
+
|
335
|
+
if pdf_image:
|
336
|
+
# Add label above the PDF image
|
337
|
+
label_height = 40
|
338
|
+
label_bg_color = (240, 240, 240)
|
339
|
+
label_text_color = (0, 0, 0)
|
340
|
+
|
341
|
+
# Create new image with space for label
|
342
|
+
width, height = pdf_image.size
|
343
|
+
labeled_image = Image.new("RGB", (width, height + label_height), "white")
|
344
|
+
|
345
|
+
# Draw label background
|
346
|
+
draw = ImageDraw.Draw(labeled_image)
|
347
|
+
draw.rectangle([0, 0, width, label_height], fill=label_bg_color)
|
348
|
+
|
349
|
+
# Draw label text
|
350
|
+
try:
|
351
|
+
# Try to use a nice font if available
|
352
|
+
font = ImageFont.truetype("Arial", 20)
|
353
|
+
except:
|
354
|
+
# Fallback to default font
|
355
|
+
font = ImageFont.load_default()
|
356
|
+
|
357
|
+
label_text = f"{pdf_name} ({len(pdf.pages)} pages)"
|
358
|
+
draw.text((10, 10), label_text, fill=label_text_color, font=font)
|
359
|
+
|
360
|
+
# Paste PDF image below label
|
361
|
+
labeled_image.paste(pdf_image, (0, label_height))
|
362
|
+
|
363
|
+
all_images.append(labeled_image)
|
364
|
+
total_pages_shown += min(pdf_limit, len(pdf.pages))
|
365
|
+
|
366
|
+
except Exception as e:
|
367
|
+
logger.warning(f"Failed to render PDF {pdf_name}: {e}")
|
368
|
+
continue
|
369
|
+
|
370
|
+
if not all_images:
|
371
|
+
print("No PDFs could be rendered")
|
372
|
+
return None
|
373
|
+
|
374
|
+
# Combine all images vertically
|
375
|
+
if len(all_images) == 1:
|
376
|
+
combined = all_images[0]
|
377
|
+
else:
|
378
|
+
# Add spacing between PDFs
|
379
|
+
spacing = 20
|
380
|
+
total_height = sum(img.height for img in all_images) + spacing * (len(all_images) - 1)
|
381
|
+
max_width = max(img.width for img in all_images)
|
382
|
+
|
383
|
+
combined = Image.new("RGB", (max_width, total_height), "white")
|
384
|
+
|
385
|
+
y_offset = 0
|
386
|
+
for i, img in enumerate(all_images):
|
387
|
+
# Center images if they're narrower than max width
|
388
|
+
x_offset = (max_width - img.width) // 2
|
389
|
+
combined.paste(img, (x_offset, y_offset))
|
390
|
+
y_offset += img.height
|
391
|
+
if i < len(all_images) - 1:
|
392
|
+
y_offset += spacing
|
393
|
+
|
394
|
+
# Return the combined image (Jupyter will display it automatically)
|
395
|
+
return combined
|
396
|
+
|
270
397
|
@overload
|
271
398
|
def find_all(
|
272
399
|
self,
|
natural_pdf/core/render_spec.py
CHANGED
@@ -92,6 +92,50 @@ class Visualizable:
|
|
92
92
|
_get_render_specs() to gain full image generation capabilities.
|
93
93
|
"""
|
94
94
|
|
95
|
+
def highlight(self, *elements, **kwargs):
|
96
|
+
"""
|
97
|
+
Convenience method for highlighting elements in Jupyter/Colab.
|
98
|
+
|
99
|
+
This method creates a highlight context, adds the elements, and returns
|
100
|
+
the resulting image. It's designed for simple one-liner usage in notebooks.
|
101
|
+
|
102
|
+
Args:
|
103
|
+
*elements: Elements or element collections to highlight
|
104
|
+
**kwargs: Additional parameters passed to show()
|
105
|
+
|
106
|
+
Returns:
|
107
|
+
PIL Image with highlights
|
108
|
+
|
109
|
+
Example:
|
110
|
+
# Simple one-liner highlighting
|
111
|
+
page.highlight(left, mid, right)
|
112
|
+
|
113
|
+
# With custom colors
|
114
|
+
page.highlight(
|
115
|
+
(tables, 'blue'),
|
116
|
+
(headers, 'red'),
|
117
|
+
(footers, 'green')
|
118
|
+
)
|
119
|
+
"""
|
120
|
+
from natural_pdf.core.highlighting_service import HighlightContext
|
121
|
+
|
122
|
+
# Create context and add elements
|
123
|
+
ctx = HighlightContext(self, show_on_exit=False)
|
124
|
+
|
125
|
+
for element in elements:
|
126
|
+
if isinstance(element, tuple) and len(element) == 2:
|
127
|
+
# Element with color: (element, color)
|
128
|
+
ctx.add(element[0], color=element[1])
|
129
|
+
elif isinstance(element, tuple) and len(element) == 3:
|
130
|
+
# Element with color and label: (element, color, label)
|
131
|
+
ctx.add(element[0], color=element[1], label=element[2])
|
132
|
+
else:
|
133
|
+
# Just element
|
134
|
+
ctx.add(element)
|
135
|
+
|
136
|
+
# Return the image directly
|
137
|
+
return ctx.show(**kwargs)
|
138
|
+
|
95
139
|
def _get_render_specs(
|
96
140
|
self, mode: Literal["show", "render"] = "show", **kwargs
|
97
141
|
) -> List[RenderSpec]:
|
@@ -142,7 +186,7 @@ class Visualizable:
|
|
142
186
|
color: Optional[Union[str, Tuple[int, int, int]]] = None,
|
143
187
|
labels: bool = True,
|
144
188
|
label_format: Optional[str] = None,
|
145
|
-
highlights: Optional[List[Dict[str, Any]]] = None,
|
189
|
+
highlights: Optional[Union[List[Dict[str, Any]], bool]] = None,
|
146
190
|
legend_position: str = "right",
|
147
191
|
annotate: Optional[Union[str, List[str]]] = None,
|
148
192
|
# Layout options for multi-page/region
|
@@ -167,7 +211,7 @@ class Visualizable:
|
|
167
211
|
color: Default highlight color
|
168
212
|
labels: Whether to show labels for highlights
|
169
213
|
label_format: Format string for labels (e.g., "Element {index}")
|
170
|
-
highlights: Additional highlight groups to show
|
214
|
+
highlights: Additional highlight groups to show, or False to disable all highlights
|
171
215
|
legend_position: Position of legend/colorbar ('right', 'left', 'top', 'bottom')
|
172
216
|
annotate: Attribute name(s) to display on highlights (string or list)
|
173
217
|
layout: How to arrange multiple pages/regions (defaults to 'grid' for multi-page, 'single' for single page)
|
natural_pdf/elements/base.py
CHANGED
@@ -429,8 +429,28 @@ class DirectionalMixin:
|
|
429
429
|
def to_region(self):
|
430
430
|
return self.expand()
|
431
431
|
|
432
|
+
@overload
|
433
|
+
def expand(self, amount: float) -> "Region":
|
434
|
+
"""Expand in all directions by the same amount."""
|
435
|
+
...
|
436
|
+
|
437
|
+
@overload
|
432
438
|
def expand(
|
433
439
|
self,
|
440
|
+
*,
|
441
|
+
left: float = 0,
|
442
|
+
right: float = 0,
|
443
|
+
top: float = 0,
|
444
|
+
bottom: float = 0,
|
445
|
+
width_factor: float = 1.0,
|
446
|
+
height_factor: float = 1.0,
|
447
|
+
) -> "Region":
|
448
|
+
"""Expand by different amounts in each direction."""
|
449
|
+
...
|
450
|
+
|
451
|
+
def expand(
|
452
|
+
self,
|
453
|
+
amount: Optional[float] = None,
|
434
454
|
left: float = 0,
|
435
455
|
right: float = 0,
|
436
456
|
top: float = 0,
|
@@ -442,6 +462,7 @@ class DirectionalMixin:
|
|
442
462
|
Create a new region expanded from this element/region.
|
443
463
|
|
444
464
|
Args:
|
465
|
+
amount: If provided as the first positional argument, expand all edges by this amount
|
445
466
|
left: Amount to expand left edge (positive value expands leftwards)
|
446
467
|
right: Amount to expand right edge (positive value expands rightwards)
|
447
468
|
top: Amount to expand top edge (positive value expands upwards)
|
@@ -451,7 +472,20 @@ class DirectionalMixin:
|
|
451
472
|
|
452
473
|
Returns:
|
453
474
|
New expanded Region object
|
475
|
+
|
476
|
+
Examples:
|
477
|
+
# Expand 5 pixels in all directions
|
478
|
+
expanded = element.expand(5)
|
479
|
+
|
480
|
+
# Expand by different amounts in each direction
|
481
|
+
expanded = element.expand(left=10, right=5, top=3, bottom=7)
|
482
|
+
|
483
|
+
# Use width/height factors
|
484
|
+
expanded = element.expand(width_factor=1.5, height_factor=2.0)
|
454
485
|
"""
|
486
|
+
# If amount is provided as first positional argument, use it for all directions
|
487
|
+
if amount is not None:
|
488
|
+
left = right = top = bottom = amount
|
455
489
|
# Start with current coordinates
|
456
490
|
new_x0 = self.x0
|
457
491
|
new_x1 = self.x1
|
@@ -1158,7 +1192,7 @@ class Element(
|
|
1158
1192
|
self,
|
1159
1193
|
mode: Literal["show", "render"] = "show",
|
1160
1194
|
color: Optional[Union[str, Tuple[int, int, int]]] = None,
|
1161
|
-
highlights: Optional[List[Dict[str, Any]]] = None,
|
1195
|
+
highlights: Optional[Union[List[Dict[str, Any]], bool]] = None,
|
1162
1196
|
crop: Union[bool, Literal["content"]] = False,
|
1163
1197
|
crop_bbox: Optional[Tuple[float, float, float, float]] = None,
|
1164
1198
|
label: Optional[str] = None,
|
@@ -1169,7 +1203,7 @@ class Element(
|
|
1169
1203
|
Args:
|
1170
1204
|
mode: Rendering mode - 'show' includes highlights, 'render' is clean
|
1171
1205
|
color: Color for highlighting this element in show mode
|
1172
|
-
highlights: Additional highlight groups to show
|
1206
|
+
highlights: Additional highlight groups to show, or False to disable all highlights
|
1173
1207
|
crop: Whether to crop to element bounds
|
1174
1208
|
crop_bbox: Explicit crop bounds
|
1175
1209
|
label: Optional label for this element
|
@@ -1191,19 +1225,23 @@ class Element(
|
|
1191
1225
|
if hasattr(self, "bbox") and self.bbox:
|
1192
1226
|
spec.crop_bbox = self.bbox
|
1193
1227
|
|
1194
|
-
# Add highlight in show mode
|
1195
|
-
if mode == "show":
|
1196
|
-
#
|
1197
|
-
|
1198
|
-
|
1199
|
-
|
1200
|
-
|
1201
|
-
|
1202
|
-
|
1203
|
-
|
1228
|
+
# Add highlight in show mode (unless explicitly disabled with highlights=False)
|
1229
|
+
if mode == "show" and highlights is not False:
|
1230
|
+
# Only highlight this element if:
|
1231
|
+
# 1. We're not cropping, OR
|
1232
|
+
# 2. We're cropping but color was explicitly specified
|
1233
|
+
if not crop or color is not None:
|
1234
|
+
# Use provided label or generate one
|
1235
|
+
element_label = label if label is not None else self.__class__.__name__
|
1236
|
+
|
1237
|
+
spec.add_highlight(
|
1238
|
+
element=self,
|
1239
|
+
color=color or "red", # Default red for single element
|
1240
|
+
label=element_label,
|
1241
|
+
)
|
1204
1242
|
|
1205
|
-
# Add additional highlight groups if provided
|
1206
|
-
if highlights:
|
1243
|
+
# Add additional highlight groups if provided (and highlights is a list)
|
1244
|
+
if highlights and isinstance(highlights, list):
|
1207
1245
|
for group in highlights:
|
1208
1246
|
group_elements = group.get("elements", [])
|
1209
1247
|
group_color = group.get("color", color)
|
@@ -1260,7 +1298,7 @@ class Element(
|
|
1260
1298
|
self,
|
1261
1299
|
*,
|
1262
1300
|
text: str,
|
1263
|
-
|
1301
|
+
overlap: str = "full",
|
1264
1302
|
apply_exclusions: bool = True,
|
1265
1303
|
regex: bool = False,
|
1266
1304
|
case: bool = True,
|
@@ -1272,7 +1310,7 @@ class Element(
|
|
1272
1310
|
self,
|
1273
1311
|
selector: str,
|
1274
1312
|
*,
|
1275
|
-
|
1313
|
+
overlap: str = "full",
|
1276
1314
|
apply_exclusions: bool = True,
|
1277
1315
|
regex: bool = False,
|
1278
1316
|
case: bool = True,
|
@@ -1284,7 +1322,7 @@ class Element(
|
|
1284
1322
|
selector: Optional[str] = None,
|
1285
1323
|
*,
|
1286
1324
|
text: Optional[str] = None,
|
1287
|
-
|
1325
|
+
overlap: str = "full",
|
1288
1326
|
apply_exclusions: bool = True,
|
1289
1327
|
regex: bool = False,
|
1290
1328
|
case: bool = True,
|
@@ -1299,9 +1337,9 @@ class Element(
|
|
1299
1337
|
Args:
|
1300
1338
|
selector: CSS-like selector string.
|
1301
1339
|
text: Text content to search for (equivalent to 'text:contains(...)').
|
1302
|
-
|
1303
|
-
'
|
1304
|
-
(default: "
|
1340
|
+
overlap: How to determine if elements overlap with this element: 'full' (fully inside),
|
1341
|
+
'partial' (any overlap), or 'center' (center point inside).
|
1342
|
+
(default: "full")
|
1305
1343
|
apply_exclusions: Whether to apply exclusion regions (default: True).
|
1306
1344
|
regex: Whether to use regex for text search (`selector` or `text`) (default: False).
|
1307
1345
|
case: Whether to do case-sensitive text search (`selector` or `text`) (default: True).
|
@@ -1318,7 +1356,7 @@ class Element(
|
|
1318
1356
|
return temp_region.find(
|
1319
1357
|
selector=selector,
|
1320
1358
|
text=text,
|
1321
|
-
|
1359
|
+
overlap=overlap,
|
1322
1360
|
apply_exclusions=apply_exclusions,
|
1323
1361
|
regex=regex,
|
1324
1362
|
case=case,
|
@@ -1330,7 +1368,7 @@ class Element(
|
|
1330
1368
|
self,
|
1331
1369
|
*,
|
1332
1370
|
text: str,
|
1333
|
-
|
1371
|
+
overlap: str = "full",
|
1334
1372
|
apply_exclusions: bool = True,
|
1335
1373
|
regex: bool = False,
|
1336
1374
|
case: bool = True,
|
@@ -1342,7 +1380,7 @@ class Element(
|
|
1342
1380
|
self,
|
1343
1381
|
selector: str,
|
1344
1382
|
*,
|
1345
|
-
|
1383
|
+
overlap: str = "full",
|
1346
1384
|
apply_exclusions: bool = True,
|
1347
1385
|
regex: bool = False,
|
1348
1386
|
case: bool = True,
|
@@ -1354,7 +1392,7 @@ class Element(
|
|
1354
1392
|
selector: Optional[str] = None,
|
1355
1393
|
*,
|
1356
1394
|
text: Optional[str] = None,
|
1357
|
-
|
1395
|
+
overlap: str = "full",
|
1358
1396
|
apply_exclusions: bool = True,
|
1359
1397
|
regex: bool = False,
|
1360
1398
|
case: bool = True,
|
@@ -1369,9 +1407,9 @@ class Element(
|
|
1369
1407
|
Args:
|
1370
1408
|
selector: CSS-like selector string.
|
1371
1409
|
text: Text content to search for (equivalent to 'text:contains(...)').
|
1372
|
-
|
1373
|
-
'
|
1374
|
-
(default: "
|
1410
|
+
overlap: How to determine if elements overlap with this element: 'full' (fully inside),
|
1411
|
+
'partial' (any overlap), or 'center' (center point inside).
|
1412
|
+
(default: "full")
|
1375
1413
|
apply_exclusions: Whether to apply exclusion regions (default: True).
|
1376
1414
|
regex: Whether to use regex for text search (`selector` or `text`) (default: False).
|
1377
1415
|
case: Whether to do case-sensitive text search (`selector` or `text`) (default: True).
|
@@ -1388,7 +1426,7 @@ class Element(
|
|
1388
1426
|
return temp_region.find_all(
|
1389
1427
|
selector=selector,
|
1390
1428
|
text=text,
|
1391
|
-
|
1429
|
+
overlap=overlap,
|
1392
1430
|
apply_exclusions=apply_exclusions,
|
1393
1431
|
regex=regex,
|
1394
1432
|
case=case,
|