Split Helpers
Crop each segment of a split into its own file with docutray.split — crop_segment, expand_box, segment_pieces and the docutray[split] extra.
Crop each segment of a split into its own file, ready for client.convert.
Cropping needs the optional split extra (pypdf, pypdfium2, Pillow and
cryptography, which pypdf needs to read AES-encrypted PDFs such as those with
only an owner password):
pip install "docutray[split]"expand_box and segment_pieces need none of them, and neither
does a segment of an image that covers the whole image. The dependencies are
imported the first time a crop needs them; when they are missing,
crop_segment raises an ImportError that says what to install.
Example:
>>> from pathlib import Path
>>> from docutray import Client
>>> from docutray.split import crop_segment
>>>
>>> client = Client()
>>> path = Path("bundle.pdf")
>>> split = client.split.create(
... file=path, document_type_code_options=["factura", "boleta"]
... )
>>> # Keep split.split_id: after a timeout, resume with
>>> # client.split.wait(split.split_id), never with a second create().
>>> result = split.wait()
>>> if result.is_failed():
... raise RuntimeError(f"Split failed: {result.error}")
>>> conversions = []
>>> for segment in result.segments or []:
... if segment.document_type.code == "otro":
... continue
... crop = crop_segment(path, segment)
... conversions.append(
... client.convert.run_async(
... file=crop.as_file(), # bytes named segment-<index>-<code>.<ext>
... content_type=crop.content_type,
... document_type_code=segment.document_type.code,
... document_metadata={
... "split_id": result.split_id,
... "segment_index": segment.index,
... },
... )
... )
>>> for conversion in conversions:
... final = conversion.wait()
... print(final.status, final.data)Constants
-
SPLIT_CROP_MARGIN = 0.02- Margin added on each side of a region: 2 % of the page width and height. -
SPLIT_RENDER_DPI = 200- Resolution at which PDF pages are rendered to crop them by region.
Functions
crop_segment
def crop_segment(file: Path | str | bytes | BinaryIO, segment: SplitSegment | dict[str, Any], *, content_type: str | None = None, margin: float = SPLIT_CROP_MARGIN, dpi: int = SPLIT_RENDER_DPI) -> CroppedSegmentCrop a segment of a split out of the original file.
regionsisNone, or every region is a whole page: a PDF gives a new PDF with the segment's pages, copied without rendering (an owner-encrypted PDF is decrypted on the way); an image is returned as-is.- Otherwise it crops by region, with the margin: a PDF page is rendered at
dpifirst; an image is read with its EXIF orientation applied. One region gives a PNG; several pieces give a PDF with one page per piece. A page without a region goes whole.
Arguments:
file: The same file that was split: a path, its bytes or a binary file.
segment: A segment from split.get_status() or wait() (or its dict).
content_type: MIME type of the file. Detected from the path or the bytes
when omitted.
margin: Margin on each side of a region. Defaults to 2 %.
dpi: Resolution for rendering PDF pages. Defaults to 200.
Raises:
ImportError: If the split extra is not installed and the crop needs it.
ValueError: If the file type is unsupported or a page is out of range.
expand_box
def expand_box(box: SplitBox, margin: float = SPLIT_CROP_MARGIN) -> SplitBoxThe region plus a margin on each side, kept inside the page.
Each coordinate is clamped to [0, 1]. The boxes of a split are tight; the margin keeps the edges of the paper.
segment_pieces
def segment_pieces(segment: SplitSegment) -> list[SegmentPiece]What to send for a segment, in order.
One piece per region, and the whole page for a page of the segment without a
region (Docutray never puts a page without a region in two segments). With
regions set to None every page is whole.
CroppedSegment
The file to convert for a segment.
Methods:
as_file
def as_file(self) -> io.BytesIOcontent as a binary file named filename.
Pass it as file to client.convert (with content_type) so the
upload carries the segment's filename.
Fields:
-
content:bytes- The bytes; pass them asfiletoclient.convert. -
content_type:str- MIME type ofcontent. -
extension:str- Extension ofcontent, with the dot (.pdf,.png, ...). -
filename:str-segment-<index>-<code><extension>. -
method:Literal['pages', 'rendered']-pages: PDF pages copied (or the image as-is), without rendering;rendered: pages rendered or images decoded, and cropped.
SegmentPiece
One piece of a segment: a page, and the box to crop or None (whole).
Fields:
-
page:int -
box:SplitBox | None