Partition
Documentation for Aryn SDK Partition
Please find the documentation for the Aryn SDK Partition module below. All parameters are optional unless specified otherwise.
partition_file
Sends a file to Aryn DocParse and returns a Python dictionary with elements containing its document structure and text.
file
: Required. Afile
opened in binary mode to parse or a path expressed as astr
or aPathLike
object specifying where the file to parse is.threshold
: Either the specificstring
auto
or afloat
between0.0
and1.0
, inclusive. This value specifies the cutoff for detecting bounding boxes. It defaults toauto
, where the service uses a processing method to find the best prediction for each possible bounding box. This is the recommended setting. However, this can be overridden by specifying a numerical threshold between 0 and 1. If you specify a numerical threshold, only bounding boxes with confidence scores higher than the threshold will be returned. A lower value will include more objects but may have overlaps, while a higher value will reduce the number of overlaps but may miss legitimate objects. If you do set the threshold manually, we recommend starting with a value of0.32
.use_ocr
: A boolean value that, when set toTrue
, causes DocParse to extract text using an OCR model. This is useful when the text is not directly extractable from the PDF, such as when the text is part of an image or when the text is rotated. When set toFalse
, DocParse extracts embedded text from the input document. Default isFalse
.extract_table_structure
: A boolean that, whenTrue
, enables DocParse to extract tables and their structural content partitioner using a purpose built table extraction model. If set toFalse
, tables are still identified but not analyzed for their structure; as a result, table cells and their bounding boxes are not included in the response. Default isFalse
.table_extraction_options
: A map with string keys specifying options for table extraction, which currently only supports the booleaninclude_additional_text
, which will add in text from OCR boxes. When include_additional_text is set to true and table extraction is enabled, DocParse will attempt to enhance the table structure by merging in tokens from text extraction. This can be useful for working with tables that have missing or misaligned text.include_additional_text
isFalse
by default. The default table_extraction_options is{}
.extract_images
: A boolean that determines whether to extract images from the document. Default:False
.ocr_images
: A boolean that, whenTrue
, causes DocParse to use OCR to attempt to generate a text representation of detected images. WhenFalse
, images do not contain a text_representation. Default isFalse
.selected_pages
: A list specifying individual pages (1-indexed) and page ranges from the document to partition. Single pages are specified as integers and ranges are specified as lists with two integer entries in ascending order. A valid example value for selected_pages is[1, 10, [15, 20]]
which would include pages 1, 10, 15, 16, 17 …, 20.selected_pages
isNone
by default, which results in all pages of the document being parsed.chunking_options
: A dictionary of options for specifying chunking behavior. Chunking is only performed when this option is present, and default options are chosen whenchunking_options
is specified as{}
.strategy
: A string specifying the strategy to use to combine and split chunks. Valid values arecontext_rich
andmaximize_within_limit
. The default and recommended chunker iscontext_rich
as{'strategy': 'context_rich'}
.-
Behavior of
context_rich
chunker: The goal of this strategy is to add context to evenly-sized chunks. This is most useful for retrieval based GenAI applications. Context_rich chunking combines adjacentsection-header
andtitle
elements into a newsection-header
element. Merges elements into a chunk with its most recentsection-header
. If the chunk would contain too many tokens, then it starts a new chunk copying the section-header to the start of this new chunk and continues. Merges elements on different pages, unlessmerge_across_pages
is set toFalse
. -
Behavior of
maximize_within_limit
chunker: The goal of themaximize_within_limit
chunker is to make the chunks as large as possible. Merges elements into the last most recently merged set of elements unless doing so would make its token count exceedmax_tokens
. In that case, it would keep the new element separate and start merging subsequent elements into that one, following the same rule. Merges elements on different pages, unlessmerge_across_pages
is set toFalse
.
-
max_tokens
: An integer specifying the cutoff for splitting chunks that are too large. Default value is 512.tokenizer
: A string specifying the tokenizer to use when determining how characters in a chunk are grouped. Valid values areopenai_tokenizer
,character_tokenizer
, andhuggingface_tokenizer
. Defaults toopenai_tokenizer
.tokenizer_options
: A tree with string keys specifying the options for the chosen tokenizer. Defaults to{'model_name': 'text-embedding-3-small'}
, which works with the OpenAI tokenizer.- Available options for
openai_tokenizer
:model_name
: Accepts all models supported by OpenAI’s tiktoken tokenizer. Default is “text-embedding-3-small”
- Available options for
HuggingFaceTokenizer
:model_name
: Accepts all huggingface tokenizers from the huggingface/tokenizers repo.
character_tokenizer
does not take any options.
- Available options for
merge_across_pages
: Aboolean
that whenTrue
the selected chunker will attempt to merge chunks across page boundaries. Does not apply to themixed_multi_column
merger, which never merges across pages. Defaults toTrue
.
output_format
: A string controlling the output representation. Defaults tojson
which yields an array calledelements
which contains the partitioned elements, represented in JSON. If set tomarkdown
the service response will instead include a field calledmarkdown
that contains a string representing the entire document in Markdown format.aps_url
: Astring
specifying the URL of the Aryn DocParse endpoint. Default URL: “https://api.aryn.cloud/v1/document/partition”.ssl_verify
: Aboolean
that controls whether the client verifies the SSL certificate of the chosen DocParse server. In Databricks, set this toFalse
to fix SSL incompatibilities. ssl_verify isTrue
by default, enforcing SSL verification.aryn_api_key
: An Aryn API key, provided as a string. You can get one for free at aryn.ai/get-started. Default isNone
(aryn-sdk will look for it in the aryn_config parameter (which by default looks in ~/.aryn/config.yaml and then in your environment variables (ARYN_API_KEY
by default))).aryn_config
: An ArynConfig object (defined in aryn_sdk/config.py), used for finding an api key. If aryn_api_key is set it will override this. The default ArynConfig looks in the env varARYN_API_KEY
and then in the file ~/.aryn/config.yaml. Default is None (aryn-sdk will look in the aryn_api_key parameter, in your environment variables, and then in ~/.aryn/config.yaml).
A dictionary containing keys status
and elements
. If output_format is markdown
, returns a dictionary of status
and markdown
.
from aryn_sdk.partition import partition_file
with open("my-favorite-pdf.pdf", "rb") as f:
data = partition_file(
f,
aryn_api_key="MY-API-KEY",
use_ocr=True,
extract_table_structure=True,
extract_images=True
)
elements = data['elements']
convert_image_element
Convert an image element to a more usable format. If no format is specified, create a PIL Image object. If a format is specified, output the bytes of the image in that format. If b64encode
is set to True
, base64-encode the bytes and return them as a string
.
elem
: Required. An image element from theelements
field of apartition_file
response.format
: Astring
specifying the format to output bytes to. Default isPIL
.b64encode
: Aboolean
that when set to True enables base64-encoding of the output bytes of this function. Format cannot bePIL
when this option isTrue
. Default isFalse
.
Either a PIL Image
object, bytes of an image, or a base64-encoded image as a str
.
from aryn_sdk.partition import partition_file, convert_image_element
with open("my-favorite-pdf.pdf", "rb") as f:
data = partition_file(
f,
extract_images=True
)
image_elts = [e for e in data['elements'] if e['type'] == 'Image']
pil_img = convert_image_element(image_elts[0])
jpg_bytes = convert_image_element(image_elts[1], format='JPEG')
png_str = convert_image_element(image_elts[2], format="PNG", b64encode=True)
draw_with_boxes
Create a list of images from the provided PDF, one for each page, with bounding boxes detected by the partitioner drawn on.
pdf_file
: Required. A PDF file opened in binary mode or a path to a PDF file expressed as astring
or aPathLike
object upon which to draw. -partitioning_data
: Required. The output frompartition_file
.draw_table_cells
: A boolean that whenTrue
, makes the function draw individually detected cells of tables. WhenFalse
, the bounding boxes of table cells are not drawn but the outer bounding boxes of tables and the bounding boxes of all other elements are still drawn. Default is False.
A list of images of pages of the PDF, each with bounding boxes drawn on.
from aryn_sdk.partition import partition_file, draw_with_boxes
with open("my-favorite-pdf.pdf", "rb") as f:
data = partition_file(
f,
aryn_api_key="MY-ARYN-TOKEN",
use_ocr=True,
extract_table_structure=True,
extract_images=True
)
pages = draw_with_boxes("my-favorite-pdf.pdf", data, draw_table_cells=True)
table_elem_to_dataframe
Create a pandas
DataFrame representing the tabular data inside the provided table element. If the element is not of type table
or doesn’t contain any table data, return None
instead.
elem
: Required. An element from the ‘elements’ field of apartition_file
response.
A Pandas DataFrame representing the tabular data inside the provided table element. If the element is not of type ‘table’ or doesn’t contain any table data, returns None instead.
from aryn_sdk.partition import partition_file, table_elem_to_dataframe
with open("partition-me.pdf", "rb") as f:
data = partition_file(
f,
use_ocr=True,
extract_table_structure=True,
extract_images=True
)
# Find the first table and convert it to a dataframe
df = None
for element in data['elements']:
if element['type'] == 'table':
df = table_elem_to_dataframe(element)
break
tables_to_pandas
For every table element in the provided partitioning response, create a pandas DataFrame representing the tabular data. Return a list containing all the elements, with tables paired with their corresponding DataFrames.
data
: A response frompartition_file
A list of tuples, where each tuple contains an element from the ‘elements’ field of a partition_file
response and a Pandas DataFrame representing the tabular data inside the provided table element. If the element is not of type ‘table’ or doesn’t contain any table data, the DataFrame will be None
.
from aryn_sdk.partition import partition_file, tables_to_pandas
with open("my-favorite-pdf.pdf", "rb") as f:
data = partition_file(
f,
aryn_api_key="MY-ARYN-TOKEN",
use_ocr=True,
extract_table_structure=True,
extract_images=True
)
elts_and_dataframes = tables_to_pandas(data)
Was this page helpful?