CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 2 · Lesson 9/56

    Choosing a document parser: binaryFile, Python UDFs and ai_parse_document

    Choose the appropriate Python package to extract document content from provided source data and format.

    21 min read
    1.75% of exam
    6 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Load raw PDFs, images and Office files from a Unity Catalog volume as bytes with the binaryFile reader
    • Write a Python UDF that parses those bytes with an open-source library, and say what a plain-text PDF extractor loses
    • Use ai_parse_document to get layout-aware elements (text, HTML tables, figures) and handle its VARIANT output and limits
    • Pick the parsing path that fits a given source format and set of structural requirements

    Key concept

    Format-matched parsing — Each source format stores its structure differently, so the parser has to be one that reads that format's structure. For example, a plain-text extractor flattens a PDF table, but a layout-aware parser keeps it as a table. If you choose the wrong parser, the chunker and retriever only ever see what that parser kept.

    1.Why the parser decides what your RAG corpus contains

    Parsing turns raw files into text that can be chunked and embedded. Every step after it only sees what the parser produced. If a product manual's specification table comes out as one long run of numbers, no chunk size will put the rows back together. If a scanned page produces no text, retrieval can never find it. Parsing is where a RAG pipeline first loses information, and it happens before anyone has run an evaluation that would show the loss.

    The choice depends on the source format and on how much structure you need to keep. A digitally generated PDF that is mostly running prose needs very little: any extractor that returns the page text is enough. A PDF with multi-page tables, charts and scanned pages needs a parser that understands layout and can read text from images. Scanned images need optical character recognition (OCR): Tesseract is a popular open-source OCR library, and Amazon Textract, Azure AI Vision OCR and Google Cloud Vision API are SaaS alternatives. An HTML page or a Word file holds its structure in its own markup, such as tags or heading styles. For those, choose a parser that reads that markup directly. Converting the file to another format first throws the structure away.

    Whichever parser you choose, check what it actually produces. Databricks recommends reviewing a sample of parsed output by hand on a regular basis, and logging parse errors. A file that fails to parse often points to a quality problem in the source data. Removing headers, footers and other noise once you have the text is covered in filtering extraneous content. Splitting the parsed text belongs to chunking strategy.

    Checkpoint 1 of 9· Check yourself

    A team builds a RAG app over product manuals. The manuals are PDFs with large specification tables, and the team extracts them with a plain-text extractor. Answers about specifications are poor. Inspection shows each table chunk is a long run of numbers with no row or column labels. The team has already tried several chunk sizes. What should they change?

    Sources1

    2.Loading source files as bytes with the binaryFile reader

    Every parsing path on Databricks starts with the same step: reading each file as raw bytes. The binaryFile data source reads binary files and turns each file into one row. Each row holds the file's contents and metadata, and you don't need any extra configuration. The source is commonly used for images, audio and PDFs that you process further downstream.

    Columns the binaryFile reader produces for each file
    ColumnTypeHolds
    pathStringTypeThe path of the file
    modificationTimeTimestampTypeWhen the file was last modified (may be a default value on some filesystems)
    lengthLongTypeFile length in bytes
    contentBinaryTypeThe file's raw bytes, which is what a parser consumes

    Two reader options control which files are loaded. pathGlobFilter keeps only the paths that match a pattern such as *.pdf, and partition discovery still runs. recursiveFileLookup searches nested directories even when their names don't follow a partition scheme like date=2019-07-01, and it skips partition discovery. In SQL, read_files(..., format => 'binaryFile') returns the same rows. That makes it the natural input for a SQL parsing function.

    Recursively read only matching files from a Unity Catalog volume as bytespython
    df = (spark.read.format("binaryFile")
      .option("pathGlobFilter", "*.jpg")
      .option("recursiveFileLookup", "true")
      .load("/Volumes/<catalog>/<schema>/<volume>/images/"))

    The content column is what links the reader to the parser. Both the managed function and any open-source parser take document bytes as input. A binary column in a DataFrame or Delta table satisfies that, and when the files are in a volume, the binaryFile reader is how you produce that column.

    Checkpoint 2 of 9· Fill the gap

    A team wants to pass every JPG in a Unity Catalog volume to ai_parse_document. The volume has nested folders. The function needs a column that holds each file's raw bytes. Which data source format completes the reader?

    df = (spark.read.format(" ? ")
      .option("pathGlobFilter", "*.jpg")
      .option("recursiveFileLookup", "true")
      .load("/Volumes/<catalog>/<schema>/<volume>/images/"))

    Sources23

    3.Parsing bytes with an open-source library in a UDF

    Use an open-source parser when the managed function isn't available, for example because AI functions aren't offered in your region, or when the format calls for a library that reads its markup directly. You wrap the library in a Python UDF that takes the content bytes and returns extracted text. The library is just an import inside the UDF, so you can use whichever one reads your format's structure.

    A PDF text-extraction UDF built on PyPDF2, applied to binaryFile contentpython
    from pyspark.sql.functions import udf
    from pyspark.sql.types import StringType
    from PyPDF2 import PdfReader
    import io
    
    @udf(returnType=StringType())
    def extract_pdf_text(content):
        if content is None:
            return None
        try:
            reader = PdfReader(io.BytesIO(content))
            return "\n".join(page.extract_text() or "" for page in reader.pages)
        except Exception as e:
            return f"Error: {str(e)}"

    The return type answers the question. Each file becomes a single string of page text joined by newlines. A table's cells come out as plain text, with nothing marking rows, columns or a table that continues on the next page. A page that is only a scanned image has no text to extract, so extract_text() returns nothing, and the or "" turns that into an empty string without raising an error. The UDF looks like it worked, and the page has quietly disappeared from the corpus. For a corpus of mostly prose PDFs this extractor is cheap and works well. When you need tables and scanned pages, it is the wrong tool.

    The error handling is deliberate. If a single corrupt file raised an exception, the whole Spark job would fail. Here the try block turns the failure into an Error: string, so you can count and inspect those rows afterwards. You still need to review a sample of them, because an empty string that came from a scanned page doesn't look like an error.

    The library you import depends on the format. Off-the-shelf libraries such as unstructured and PyPDF2 handle text documents like PDFs and Word files, and offer options for customizing the parsing. HTML parsing libraries such as BeautifulSoup and lxml are built for web pages: they navigate the HTML structure, select specific elements and extract the text or attributes you want, so they fit a requirement like keeping only the elements with one CSS class. Images and scanned documents need OCR, for example the open-source Tesseract library. Each library reads one kind of structure. BeautifulSoup is the wrong tool for a binary PDF, and PyPDF2 reads the text a PDF already holds rather than recognizing text in an image.

    The Beta FILE column type gives you another way to pass files to a UDF. Inside the UDF, as_local_file() returns a local path for libraries that expect a file path, and open() streams only the bytes you request. A session-scoped UDF is one defined inside your running session, like the @udf functions above, and it can read file contents. A UDF registered in Unity Catalog with CREATE FUNCTION can read only a FILE's metadata.

    Checkpoint 3 of 9· Check yourself

    Your workspace is in a region where AI functions aren't offered. The corpus is digitally generated PDFs that are mostly running prose, already loaded with the binaryFile reader. Which approach extracts their text?

    Checkpoint 4 of 9· Check yourself

    To share it across teams, an engineer registers a Python UDF in Unity Catalog with CREATE FUNCTION. The UDF takes a FILE column and calls as_local_file() to hand each document to a parsing library. It can't read the documents. What fixes it?

    Sources415

    4.Managed, layout-aware parsing with ai_parse_document

    ai_parse_document is the managed alternative to a UDF. It is a SQL function, also available in PySpark, that takes the binary content column and returns the document as a sequence of typed elements instead of one flat string. It finds layout information such as page numbers, headers, tables and footers, and then extracts the content inside each element. A Databricks-managed model served through Foundation Model APIs does the work. You can't customize that model or replace it with your own.

    Parse every document in a volume, reading bytes with binaryFile and pinning output schema 2.0sql
    SELECT
      ai_parse_document(
        content,
        map('version', '2.0')
      ) AS parsed
    FROM READ_FILES('/Volumes/my_catalog/my_schema/my_documents', format => 'binaryFile');

    The supported inputs are PDF, JPG/JPEG, PNG, TIFF/TIF, DOC/DOCX and PPT/PPTX. Images are accepted, so text is extracted from image pages as well as from digital text. In output schema 2.0, each element has a type (text, table, figure, signature, title, caption, section_header, page_header, page_footer, page_number or footnote), a content string, a confidence score from 0 to 1, and a bbox giving its location on the page. Table elements contain their content as HTML, so rows and columns survive parsing. Charts come back as figure elements, and their content holds JSON chart data when the values can be read. Because of these typed elements, the function fits structure-aware chunking well, and you can drop page headers and footers by their type.

    ai_parse_document options (all optional; content is the only required argument)
    OptionEffect
    versionPins the output schema version; "2.0" is supported
    imageOutputPathSaves rendered page images to a Unity Catalog volume, for reference or multi-modal RAG
    descriptionElementTypes'*' (default) or 'figure' generates AI figure descriptions; '' turns them off to cut compute and cost on figure-heavy documents
    pageRangeParses only listed 1-indexed pages, e.g. '1,3,5-10'; selected pages must stay within the 500-page limit

    The function has hard limits that a pipeline has to plan for:

    • Documents can have at most 500 pages and files can be at most 100 MB. REST API calls are capped at 100 pages per document and, by default, 250 requests per minute per workspace.
    • It needs Databricks Runtime 17.3 or above. On serverless, the environment version must be 3 or above, which enables VARIANT. It is available only in some regions.
    • Results can be weaker on images with non-Latin text such as Japanese or Korean, and on documents that carry digital signatures. Dense or low-resolution content can be slow to parse, or parts of it can be skipped.

    The output is a VARIANT. You can extract fields from it in SQL, for example parsed:document:elements. PySpark can't collect a VARIANT directly, though, so convert it with to_json() in SQL and then call json.loads() on each row in Python. Costs are recorded under the AI_FUNCTIONS product. Before running a schema across a whole corpus, open the Document Parsing UI in Agent Bricks, which shows each source document next to its parsed output. It also generates the query for you to run on more files.

    Checkpoint 5 of 9· Match them up

    Match each ai_parse_document option to the pipeline need it meets

    Tap a term, then the definition that fits it.

    Sources36

    5.Matching the format and requirement to a parsing path

    Make the choice by asking two questions in order. First, is the format one that ai_parse_document accepts, and does the content need layout, such as tables, charts, scanned pages or mixed text and images? If it does, use the managed function. A UDF would have to add its own layout and text-recognition handling to match it on tables and image text. Second, if the format isn't in that list, or the structure you need is already in the file's own markup, wrap a parser that reads that markup in a UDF. HTML is the clearest example. It isn't one of the supported inputs, and its structure lives in its tags and CSS classes.

    Which parsing path fits which source
    Source and requirementPathWhy
    PDFs with multi-page tables, charts or scanned pagesai_parse_documentTyped elements; tables as HTML; image formats supported; charts as figure JSON
    Digital PDFs that are mostly prose; AI functions unavailablePyPDF2 UDF over binaryFile contentCheap per-page text; returns one flat string, so tables and image-only pages are lost
    DOC/DOCX or PPT/PPTX needing headings and sectionsai_parse_document, or a UDF with a library such as unstructuredBoth formats are supported inputs; section_header and title elements carry the hierarchy
    HTML pages selected by tag or CSS classUDF with BeautifulSoup or lxmlHTML is not a supported ai_parse_document input; these libraries navigate the HTML structure and select specific elements
    Scanned images or documents when AI functions are unavailableUDF with an OCR library such as TesseractOCR is typically required to extract text from images
    Standalone images needing a short descriptionai_query with files => contentSends the image bytes to a multimodal model and returns text

    Each library in the table reads one kind of structure, so a mismatch returns nothing useful. BeautifulSoup, usually paired with lxml, reads HTML: it walks the tags and lets you select elements by tag or CSS class, which is why it fits a requirement like "keep only the elements with this class". The unstructured library is a general-purpose parser for text documents such as PDFs and Word files, with options for customizing the parse. For a Word file that needs its headings kept, either ai_parse_document (which returns section_header and title elements) or a document library such as unstructured fits. BeautifulSoup does not, because it reads HTML markup rather than a Word file. Tesseract does not either, because OCR is for text locked in images, and a Word file already contains its text.

    Avoid converting files between formats just to make a parser fit. A conversion can only carry over what the first format exposed, and running a parser built for one markup language on a binary PDF returns nothing useful. Libraries such as LangChain and LlamaIndex include built-in parsers that extract standard metadata automatically. Supplement that with custom metadata for your use case, such as file path, section headers and page numbers. The element output of ai_parse_document already contains much of this.

    Checkpoint 6 of 9· Match them up

    A knowledge-base team has four source collections to ingest. Pair each collection and its requirement with the parsing path that fits it.

    Tap a term, then the definition that fits it.

    Checkpoint 7 of 9· Exam question

    A team is building a RAG corpus from PDF product manuals that contain large multi-page tables needing to stay structured, plus several pages that are scanned images requiring text recognition. Which approach best extracts this content?

    Checkpoint 8 of 9· Exam question

    A developer is scraping crawled HTML pages from a documentation website and needs to strip navigation bars, headers, and footers while selecting only the article body using specific CSS classes and tag hierarchy. Which package fits this need?

    Checkpoint 9 of 9· Exam question

    An internal knowledge base consists exclusively of Microsoft Word .docx files with heading styles and paragraph formatting that must be preserved for structure-aware chunking. Which package should the engineer use to extract this content?

    Sources61

    Practise it for real

    Parse a folder of PDFs in a Unity Catalog volume both ways and compare what each path keeps.

    1. 1.Load the PDFs with spark.read.format("binaryFile") and the option pathGlobFilter set to "*.pdf", then display path, length and modificationTime.

      Why: Confirms the files are visible and that each one is a single row with a binary content column.

      You should see: One row per PDF, with a non-zero length for each.

    2. 2.Apply the PyPDF2 extract_pdf_text UDF to the content column and display path alongside text_content.

      Why: Shows what a plain-text extractor produces for your documents.

      You should see: One string per file. Tables appear as unstructured text, and scanned pages show up as empty stretches.

    3. 3.Run ai_parse_document(content, map('version', '2.0')) over the same files with READ_FILES(..., format => 'binaryFile'), selecting parsed:document:elements and parsed:error_status.

      Why: Produces typed elements you can compare with the flat string.

      You should see: An elements array with table elements whose content is HTML, plus any per-page errors in error_status.

    4. 4.Wrap the parsed column in to_json() and load a few rows in Python with json.loads(), then count elements by type.

      Why: PySpark can't collect VARIANT directly, and counting element types shows what layout the parser found.

      You should see: Python dicts that include counts of text, table, figure, page_header and page_footer elements.

    Stuck? Get a nudge

    If a document has more than 500 pages, the call fails before parsing anything. Add map('pageRange', '1-500') and process the rest in another call.

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Parsing ensures data is clean, structured, and ready for embedding generation and AI Search.”
      ↩︎ Why the parser decides what your RAG corpus contains
      “Evaluating parsing quality: Regularly assess the quality of the parsed data by manually reviewing a sample of the output.”
      ↩︎ Why the parser decides what your RAG corpus contains
      “Doing so often points to upstream issues with the quality of the source data.”
      ↩︎ Why the parser decides what your RAG corpus contains
      “Popular OCR libraries include open source libraries such as Tesseract or SaaS versions like Amazon Textract, Azure AI Vision OCR, and Google Cloud Vision API.”
      ↩︎ Why the parser decides what your RAG corpus contains
      “Off-the-shelf libraries like unstructured and PyPDF2 can handle various file formats and provide options for customizing the parsing process.”
      ↩︎ Parsing bytes with an open-source library in a UDF
      “These libraries can help navigate the HTML structure, select specific elements, and extract the desired text or attributes.”
      ↩︎ Parsing bytes with an open-source library in a UDF
      “HTML parsing libraries like BeautifulSoup and lxml can be used to extract relevant content from web pages.”
      ↩︎ Matching the format and requirement to a parsing path
      “Optical Character Recognition (OCR) techniques are typically required to extract text from images.”
      ↩︎ Matching the format and requirement to a parsing path
      “While libraries such as LangChain and LlamaIndex provide built-in parsers capable of automatically extracting associated standard metadata”
      ↩︎ Matching the format and requirement to a parsing path
      “Depending on the structure and format of your data, you may need to customize the parsing logic to extract the most relevant information.”
      ↩︎ Key concept
      “HTML parsing libraries like BeautifulSoup and lxml can be used to extract relevant content from web pages.”
      ↩︎ Exam trap 3
      “Optical Character Recognition (OCR) techniques are typically required to extract text from images.”
      ↩︎ Exam trap 4
      “Depending on the structure and format of your data, you may need to customize the parsing logic to extract the most relevant information.”
      ↩︎ Checkpoint
    2. 2.
      “reads binary files and converts each file into a single record containing the file's raw content and metadata”
      ↩︎ Loading source files as bytes with the binaryFile reader
      “This option searches through nested directories even if their names do not follow a partition naming scheme like date=2019-07-01.”
      ↩︎ Loading source files as bytes with the binaryFile reader
    3. 3.
      “If the source documents are stored in a Unity Catalog volume, the binary type column can be generated using Spark binaryFile format reader.”
      ↩︎ Loading source files as bytes with the binaryFile reader
      “identifies and extracts layout information from a document, like page numbers, headers, tables, and footers, and returns them as structured elements”
      ↩︎ Managed, layout-aware parsing with ai_parse_document
      “The model powering this function is made available using Model Serving Foundation Model APIs.”
      ↩︎ Managed, layout-aware parsing with ai_parse_document
      “There is a maximum file size limit of 100 MB.”
      ↩︎ Managed, layout-aware parsing with ai_parse_document
      “The underlying model may not perform optimally when handling images using text of non-Latin alphabets, such as Japanese or Korean.”
      ↩︎ Managed, layout-aware parsing with ai_parse_document
      “It renders the source document alongside the parsed output, letting you inspect what content was extracted from each region of your documents.”
      ↩︎ Managed, layout-aware parsing with ai_parse_document
      “For version 2.0, tables are represented in HTML.”
      ↩︎ Exam trap 1
      “ai_parse_document returns a VARIANT type, which cannot be directly collected by PySpark (or other APIs that do not support VARIANT).”
      ↩︎ Exam trap 5
      “Customizing the model that powers ai_parse_document or using a customer-provided model for ai_parse_document is not supported.”
      ↩︎ Exam trap 6
      “If pageRange is omitted and the document exceeds 500 pages, the function fails immediately without parsing any pages.”
      ↩︎ Prediction
      “No descriptions are generated. This reduces the compute needed and costs for documents with lots of figures.”
      ↩︎ Checkpoint
    4. 4.
      “If you don't have access to AI functions, use standard Python libraries instead.”
      ↩︎ Parsing bytes with an open-source library in a UDF
      “If AI functions aren't available in your region, use Python libraries:”
      ↩︎ Checkpoint
    5. 5.
      “Both require Databricks compute (a notebook or UDF worker) and aren't available on a Databricks Connect client.”
      ↩︎ Parsing bytes with an open-source library in a UDF
      “A UDF registered in Unity Catalog (CREATE FUNCTION) can read a FILE's metadata, but not its contents, and it can't create files.”
      ↩︎ Exam trap 2
      “A UDF registered in Unity Catalog (CREATE FUNCTION) can read a FILE's metadata, but not its contents, and it can't create files.”
      ↩︎ Checkpoint
    6. 6.
      “ai_parse_document REST API requests are limited to 100 pages per document.”
      ↩︎ Managed, layout-aware parsing with ai_parse_document
      “It's designed to handle complex layouts such as tables, charts, and mixed text-image content.”
      ↩︎ Matching the format and requirement to a parsing path
      “Supported formats include: PDF, images, DOC/DOCX, and PPT/PPTX.”
      ↩︎ Matching the format and requirement to a parsing path

    Spotted a mistake, or was something unclear? Tell us.